xref: /linux/drivers/md/bcache/btree.c (revision 9f233ffe02e5cef611100cd8c5bcf4de26ca7bef)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2cafe5635SKent Overstreet /*
3cafe5635SKent Overstreet  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4cafe5635SKent Overstreet  *
5cafe5635SKent Overstreet  * Uses a block device as cache for other block devices; optimized for SSDs.
6cafe5635SKent Overstreet  * All allocation is done in buckets, which should match the erase block size
7cafe5635SKent Overstreet  * of the device.
8cafe5635SKent Overstreet  *
9cafe5635SKent Overstreet  * Buckets containing cached data are kept on a heap sorted by priority;
10cafe5635SKent Overstreet  * bucket priority is increased on cache hit, and periodically all the buckets
11cafe5635SKent Overstreet  * on the heap have their priority scaled down. This currently is just used as
12cafe5635SKent Overstreet  * an LRU but in the future should allow for more intelligent heuristics.
13cafe5635SKent Overstreet  *
14cafe5635SKent Overstreet  * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
15cafe5635SKent Overstreet  * counter. Garbage collection is used to remove stale pointers.
16cafe5635SKent Overstreet  *
17cafe5635SKent Overstreet  * Indexing is done via a btree; nodes are not necessarily fully sorted, rather
18cafe5635SKent Overstreet  * as keys are inserted we only sort the pages that have not yet been written.
19cafe5635SKent Overstreet  * When garbage collection is run, we resort the entire node.
20cafe5635SKent Overstreet  *
215fb94e9cSMauro Carvalho Chehab  * All configuration is done via sysfs; see Documentation/admin-guide/bcache.rst.
22cafe5635SKent Overstreet  */
23cafe5635SKent Overstreet 
24cafe5635SKent Overstreet #include "bcache.h"
25cafe5635SKent Overstreet #include "btree.h"
26cafe5635SKent Overstreet #include "debug.h"
2765d45231SKent Overstreet #include "extents.h"
28cafe5635SKent Overstreet 
29cafe5635SKent Overstreet #include <linux/slab.h>
30cafe5635SKent Overstreet #include <linux/bitops.h>
31cafe5635SKent Overstreet #include <linux/hash.h>
3272a44517SKent Overstreet #include <linux/kthread.h>
33cd953ed0SGeert Uytterhoeven #include <linux/prefetch.h>
34cafe5635SKent Overstreet #include <linux/random.h>
35cafe5635SKent Overstreet #include <linux/rcupdate.h>
36e6017571SIngo Molnar #include <linux/sched/clock.h>
37b2d09103SIngo Molnar #include <linux/rculist.h>
3850a260e8SColy Li #include <linux/delay.h>
39cafe5635SKent Overstreet #include <trace/events/bcache.h>
40cafe5635SKent Overstreet 
41cafe5635SKent Overstreet /*
42cafe5635SKent Overstreet  * Todo:
43cafe5635SKent Overstreet  * register_bcache: Return errors out to userspace correctly
44cafe5635SKent Overstreet  *
45cafe5635SKent Overstreet  * Writeback: don't undirty key until after a cache flush
46cafe5635SKent Overstreet  *
47cafe5635SKent Overstreet  * Create an iterator for key pointers
48cafe5635SKent Overstreet  *
49cafe5635SKent Overstreet  * On btree write error, mark bucket such that it won't be freed from the cache
50cafe5635SKent Overstreet  *
51cafe5635SKent Overstreet  * Journalling:
52cafe5635SKent Overstreet  *   Check for bad keys in replay
53cafe5635SKent Overstreet  *   Propagate barriers
54cafe5635SKent Overstreet  *   Refcount journal entries in journal_replay
55cafe5635SKent Overstreet  *
56cafe5635SKent Overstreet  * Garbage collection:
57cafe5635SKent Overstreet  *   Finish incremental gc
58cafe5635SKent Overstreet  *   Gc should free old UUIDs, data for invalid UUIDs
59cafe5635SKent Overstreet  *
60cafe5635SKent Overstreet  * Provide a way to list backing device UUIDs we have data cached for, and
61cafe5635SKent Overstreet  * probably how long it's been since we've seen them, and a way to invalidate
62cafe5635SKent Overstreet  * dirty data for devices that will never be attached again
63cafe5635SKent Overstreet  *
64cafe5635SKent Overstreet  * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
65cafe5635SKent Overstreet  * that based on that and how much dirty data we have we can keep writeback
66cafe5635SKent Overstreet  * from being starved
67cafe5635SKent Overstreet  *
68cafe5635SKent Overstreet  * Add a tracepoint or somesuch to watch for writeback starvation
69cafe5635SKent Overstreet  *
70cafe5635SKent Overstreet  * When btree depth > 1 and splitting an interior node, we have to make sure
71cafe5635SKent Overstreet  * alloc_bucket() cannot fail. This should be true but is not completely
72cafe5635SKent Overstreet  * obvious.
73cafe5635SKent Overstreet  *
74cafe5635SKent Overstreet  * Plugging?
75cafe5635SKent Overstreet  *
76cafe5635SKent Overstreet  * If data write is less than hard sector size of ssd, round up offset in open
77cafe5635SKent Overstreet  * bucket to the next whole sector
78cafe5635SKent Overstreet  *
79cafe5635SKent Overstreet  * Superblock needs to be fleshed out for multiple cache devices
80cafe5635SKent Overstreet  *
81cafe5635SKent Overstreet  * Add a sysfs tunable for the number of writeback IOs in flight
82cafe5635SKent Overstreet  *
83cafe5635SKent Overstreet  * Add a sysfs tunable for the number of open data buckets
84cafe5635SKent Overstreet  *
85cafe5635SKent Overstreet  * IO tracking: Can we track when one process is doing io on behalf of another?
86cafe5635SKent Overstreet  * IO tracking: Don't use just an average, weigh more recent stuff higher
87cafe5635SKent Overstreet  *
88cafe5635SKent Overstreet  * Test module load/unload
89cafe5635SKent Overstreet  */
90cafe5635SKent Overstreet 
91cafe5635SKent Overstreet #define MAX_NEED_GC		64
92cafe5635SKent Overstreet #define MAX_SAVE_PRIO		72
937f4a59deSTang Junhui #define MAX_GC_TIMES		100
945c25c4fcSTang Junhui #define MIN_GC_NODES		100
955c25c4fcSTang Junhui #define GC_SLEEP_MS		100
96cafe5635SKent Overstreet 
97cafe5635SKent Overstreet #define PTR_DIRTY_BIT		(((uint64_t) 1 << 36))
98cafe5635SKent Overstreet 
99cafe5635SKent Overstreet #define PTR_HASH(c, k)							\
100cafe5635SKent Overstreet 	(((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
101cafe5635SKent Overstreet 
102*9f233ffeSKai Krakow static struct workqueue_struct *btree_io_wq;
103*9f233ffeSKai Krakow 
104df8e8970SKent Overstreet #define insert_lock(s, b)	((b)->level <= (s)->lock)
105df8e8970SKent Overstreet 
106df8e8970SKent Overstreet 
107a85e968eSKent Overstreet static inline struct bset *write_block(struct btree *b)
108a85e968eSKent Overstreet {
1094e1ebae3SColy Li 	return ((void *) btree_bset_first(b)) + b->written * block_bytes(b->c->cache);
110a85e968eSKent Overstreet }
111a85e968eSKent Overstreet 
1122a285686SKent Overstreet static void bch_btree_init_next(struct btree *b)
1132a285686SKent Overstreet {
1142a285686SKent Overstreet 	/* If not a leaf node, always sort */
1152a285686SKent Overstreet 	if (b->level && b->keys.nsets)
1162a285686SKent Overstreet 		bch_btree_sort(&b->keys, &b->c->sort);
1172a285686SKent Overstreet 	else
1182a285686SKent Overstreet 		bch_btree_sort_lazy(&b->keys, &b->c->sort);
1192a285686SKent Overstreet 
1202a285686SKent Overstreet 	if (b->written < btree_blocks(b))
1212a285686SKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
1224a784266SColy Li 				   bset_magic(&b->c->cache->sb));
1232a285686SKent Overstreet 
1242a285686SKent Overstreet }
1252a285686SKent Overstreet 
126cafe5635SKent Overstreet /* Btree key manipulation */
127cafe5635SKent Overstreet 
1283a3b6a4eSKent Overstreet void bkey_put(struct cache_set *c, struct bkey *k)
129e7c590ebSKent Overstreet {
1306f10f7d1SColy Li 	unsigned int i;
131e7c590ebSKent Overstreet 
132e7c590ebSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
133e7c590ebSKent Overstreet 		if (ptr_available(c, k, i))
134e7c590ebSKent Overstreet 			atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
135e7c590ebSKent Overstreet }
136e7c590ebSKent Overstreet 
137cafe5635SKent Overstreet /* Btree IO */
138cafe5635SKent Overstreet 
139cafe5635SKent Overstreet static uint64_t btree_csum_set(struct btree *b, struct bset *i)
140cafe5635SKent Overstreet {
141cafe5635SKent Overstreet 	uint64_t crc = b->key.ptr[0];
142fafff81cSKent Overstreet 	void *data = (void *) i + 8, *end = bset_bkey_last(i);
143cafe5635SKent Overstreet 
144169ef1cfSKent Overstreet 	crc = bch_crc64_update(crc, data, end - data);
145c19ed23aSKent Overstreet 	return crc ^ 0xffffffffffffffffULL;
146cafe5635SKent Overstreet }
147cafe5635SKent Overstreet 
14878b77bf8SKent Overstreet void bch_btree_node_read_done(struct btree *b)
149cafe5635SKent Overstreet {
150cafe5635SKent Overstreet 	const char *err = "bad btree header";
151ee811287SKent Overstreet 	struct bset *i = btree_bset_first(b);
15257943511SKent Overstreet 	struct btree_iter *iter;
153cafe5635SKent Overstreet 
154d2f96f48SShenghui Wang 	/*
155d2f96f48SShenghui Wang 	 * c->fill_iter can allocate an iterator with more memory space
156d2f96f48SShenghui Wang 	 * than static MAX_BSETS.
157d2f96f48SShenghui Wang 	 * See the comment arount cache_set->fill_iter.
158d2f96f48SShenghui Wang 	 */
159d19936a2SKent Overstreet 	iter = mempool_alloc(&b->c->fill_iter, GFP_NOIO);
1604a784266SColy Li 	iter->size = b->c->cache->sb.bucket_size / b->c->cache->sb.block_size;
161cafe5635SKent Overstreet 	iter->used = 0;
162cafe5635SKent Overstreet 
163280481d0SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
164c052dd9aSKent Overstreet 	iter->b = &b->keys;
165280481d0SKent Overstreet #endif
166280481d0SKent Overstreet 
16757943511SKent Overstreet 	if (!i->seq)
168cafe5635SKent Overstreet 		goto err;
169cafe5635SKent Overstreet 
170cafe5635SKent Overstreet 	for (;
171a85e968eSKent Overstreet 	     b->written < btree_blocks(b) && i->seq == b->keys.set[0].data->seq;
172cafe5635SKent Overstreet 	     i = write_block(b)) {
173cafe5635SKent Overstreet 		err = "unsupported bset version";
174cafe5635SKent Overstreet 		if (i->version > BCACHE_BSET_VERSION)
175cafe5635SKent Overstreet 			goto err;
176cafe5635SKent Overstreet 
177cafe5635SKent Overstreet 		err = "bad btree header";
1784e1ebae3SColy Li 		if (b->written + set_blocks(i, block_bytes(b->c->cache)) >
179ee811287SKent Overstreet 		    btree_blocks(b))
180cafe5635SKent Overstreet 			goto err;
181cafe5635SKent Overstreet 
182cafe5635SKent Overstreet 		err = "bad magic";
1834a784266SColy Li 		if (i->magic != bset_magic(&b->c->cache->sb))
184cafe5635SKent Overstreet 			goto err;
185cafe5635SKent Overstreet 
186cafe5635SKent Overstreet 		err = "bad checksum";
187cafe5635SKent Overstreet 		switch (i->version) {
188cafe5635SKent Overstreet 		case 0:
189cafe5635SKent Overstreet 			if (i->csum != csum_set(i))
190cafe5635SKent Overstreet 				goto err;
191cafe5635SKent Overstreet 			break;
192cafe5635SKent Overstreet 		case BCACHE_BSET_VERSION:
193cafe5635SKent Overstreet 			if (i->csum != btree_csum_set(b, i))
194cafe5635SKent Overstreet 				goto err;
195cafe5635SKent Overstreet 			break;
196cafe5635SKent Overstreet 		}
197cafe5635SKent Overstreet 
198cafe5635SKent Overstreet 		err = "empty set";
199a85e968eSKent Overstreet 		if (i != b->keys.set[0].data && !i->keys)
200cafe5635SKent Overstreet 			goto err;
201cafe5635SKent Overstreet 
202fafff81cSKent Overstreet 		bch_btree_iter_push(iter, i->start, bset_bkey_last(i));
203cafe5635SKent Overstreet 
2044e1ebae3SColy Li 		b->written += set_blocks(i, block_bytes(b->c->cache));
205cafe5635SKent Overstreet 	}
206cafe5635SKent Overstreet 
207cafe5635SKent Overstreet 	err = "corrupted btree";
208cafe5635SKent Overstreet 	for (i = write_block(b);
209a85e968eSKent Overstreet 	     bset_sector_offset(&b->keys, i) < KEY_SIZE(&b->key);
2104e1ebae3SColy Li 	     i = ((void *) i) + block_bytes(b->c->cache))
211a85e968eSKent Overstreet 		if (i->seq == b->keys.set[0].data->seq)
212cafe5635SKent Overstreet 			goto err;
213cafe5635SKent Overstreet 
214a85e968eSKent Overstreet 	bch_btree_sort_and_fix_extents(&b->keys, iter, &b->c->sort);
215cafe5635SKent Overstreet 
216a85e968eSKent Overstreet 	i = b->keys.set[0].data;
217cafe5635SKent Overstreet 	err = "short btree key";
218a85e968eSKent Overstreet 	if (b->keys.set[0].size &&
219a85e968eSKent Overstreet 	    bkey_cmp(&b->key, &b->keys.set[0].end) < 0)
220cafe5635SKent Overstreet 		goto err;
221cafe5635SKent Overstreet 
222cafe5635SKent Overstreet 	if (b->written < btree_blocks(b))
223a85e968eSKent Overstreet 		bch_bset_init_next(&b->keys, write_block(b),
2244a784266SColy Li 				   bset_magic(&b->c->cache->sb));
225cafe5635SKent Overstreet out:
226d19936a2SKent Overstreet 	mempool_free(iter, &b->c->fill_iter);
22757943511SKent Overstreet 	return;
228cafe5635SKent Overstreet err:
229cafe5635SKent Overstreet 	set_btree_node_io_error(b);
23088b9f8c4SKent Overstreet 	bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
231cafe5635SKent Overstreet 			    err, PTR_BUCKET_NR(b->c, &b->key, 0),
23288b9f8c4SKent Overstreet 			    bset_block_offset(b, i), i->keys);
233cafe5635SKent Overstreet 	goto out;
234cafe5635SKent Overstreet }
235cafe5635SKent Overstreet 
2364246a0b6SChristoph Hellwig static void btree_node_read_endio(struct bio *bio)
237cafe5635SKent Overstreet {
23857943511SKent Overstreet 	struct closure *cl = bio->bi_private;
2391fae7cf0SColy Li 
24057943511SKent Overstreet 	closure_put(cl);
24157943511SKent Overstreet }
242cafe5635SKent Overstreet 
24378b77bf8SKent Overstreet static void bch_btree_node_read(struct btree *b)
24457943511SKent Overstreet {
24557943511SKent Overstreet 	uint64_t start_time = local_clock();
24657943511SKent Overstreet 	struct closure cl;
24757943511SKent Overstreet 	struct bio *bio;
248cafe5635SKent Overstreet 
249c37511b8SKent Overstreet 	trace_bcache_btree_read(b);
250c37511b8SKent Overstreet 
25157943511SKent Overstreet 	closure_init_stack(&cl);
252cafe5635SKent Overstreet 
25357943511SKent Overstreet 	bio = bch_bbio_alloc(b->c);
2544f024f37SKent Overstreet 	bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
25557943511SKent Overstreet 	bio->bi_end_io	= btree_node_read_endio;
25657943511SKent Overstreet 	bio->bi_private	= &cl;
25770fd7614SChristoph Hellwig 	bio->bi_opf = REQ_OP_READ | REQ_META;
25857943511SKent Overstreet 
259a85e968eSKent Overstreet 	bch_bio_map(bio, b->keys.set[0].data);
26057943511SKent Overstreet 
26157943511SKent Overstreet 	bch_submit_bbio(bio, b->c, &b->key, 0);
26257943511SKent Overstreet 	closure_sync(&cl);
26357943511SKent Overstreet 
2644e4cbee9SChristoph Hellwig 	if (bio->bi_status)
26557943511SKent Overstreet 		set_btree_node_io_error(b);
26657943511SKent Overstreet 
26757943511SKent Overstreet 	bch_bbio_free(bio, b->c);
26857943511SKent Overstreet 
26957943511SKent Overstreet 	if (btree_node_io_error(b))
27057943511SKent Overstreet 		goto err;
27157943511SKent Overstreet 
27257943511SKent Overstreet 	bch_btree_node_read_done(b);
27357943511SKent Overstreet 	bch_time_stats_update(&b->c->btree_read_time, start_time);
27457943511SKent Overstreet 
27557943511SKent Overstreet 	return;
27657943511SKent Overstreet err:
27761cbd250SGeert Uytterhoeven 	bch_cache_set_error(b->c, "io error reading bucket %zu",
27857943511SKent Overstreet 			    PTR_BUCKET_NR(b->c, &b->key, 0));
279cafe5635SKent Overstreet }
280cafe5635SKent Overstreet 
281cafe5635SKent Overstreet static void btree_complete_write(struct btree *b, struct btree_write *w)
282cafe5635SKent Overstreet {
283cafe5635SKent Overstreet 	if (w->prio_blocked &&
284cafe5635SKent Overstreet 	    !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
285119ba0f8SKent Overstreet 		wake_up_allocators(b->c);
286cafe5635SKent Overstreet 
287cafe5635SKent Overstreet 	if (w->journal) {
288cafe5635SKent Overstreet 		atomic_dec_bug(w->journal);
289cafe5635SKent Overstreet 		__closure_wake_up(&b->c->journal.wait);
290cafe5635SKent Overstreet 	}
291cafe5635SKent Overstreet 
292cafe5635SKent Overstreet 	w->prio_blocked	= 0;
293cafe5635SKent Overstreet 	w->journal	= NULL;
294cafe5635SKent Overstreet }
295cafe5635SKent Overstreet 
296cb7a583eSKent Overstreet static void btree_node_write_unlock(struct closure *cl)
297cb7a583eSKent Overstreet {
298cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
299cb7a583eSKent Overstreet 
300cb7a583eSKent Overstreet 	up(&b->io_mutex);
301cb7a583eSKent Overstreet }
302cb7a583eSKent Overstreet 
30357943511SKent Overstreet static void __btree_node_write_done(struct closure *cl)
304cafe5635SKent Overstreet {
305cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
306cafe5635SKent Overstreet 	struct btree_write *w = btree_prev_write(b);
307cafe5635SKent Overstreet 
308cafe5635SKent Overstreet 	bch_bbio_free(b->bio, b->c);
309cafe5635SKent Overstreet 	b->bio = NULL;
310cafe5635SKent Overstreet 	btree_complete_write(b, w);
311cafe5635SKent Overstreet 
312cafe5635SKent Overstreet 	if (btree_node_dirty(b))
313*9f233ffeSKai Krakow 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
314cafe5635SKent Overstreet 
315cb7a583eSKent Overstreet 	closure_return_with_destructor(cl, btree_node_write_unlock);
316cafe5635SKent Overstreet }
317cafe5635SKent Overstreet 
31857943511SKent Overstreet static void btree_node_write_done(struct closure *cl)
319cafe5635SKent Overstreet {
320cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
321cafe5635SKent Overstreet 
322491221f8SGuoqing Jiang 	bio_free_pages(b->bio);
32357943511SKent Overstreet 	__btree_node_write_done(cl);
324cafe5635SKent Overstreet }
325cafe5635SKent Overstreet 
3264246a0b6SChristoph Hellwig static void btree_node_write_endio(struct bio *bio)
32757943511SKent Overstreet {
32857943511SKent Overstreet 	struct closure *cl = bio->bi_private;
329cb7a583eSKent Overstreet 	struct btree *b = container_of(cl, struct btree, io);
33057943511SKent Overstreet 
3314e4cbee9SChristoph Hellwig 	if (bio->bi_status)
33257943511SKent Overstreet 		set_btree_node_io_error(b);
33357943511SKent Overstreet 
3344e4cbee9SChristoph Hellwig 	bch_bbio_count_io_errors(b->c, bio, bio->bi_status, "writing btree");
33557943511SKent Overstreet 	closure_put(cl);
33657943511SKent Overstreet }
33757943511SKent Overstreet 
33857943511SKent Overstreet static void do_btree_node_write(struct btree *b)
339cafe5635SKent Overstreet {
340cb7a583eSKent Overstreet 	struct closure *cl = &b->io;
341ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
342cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
343cafe5635SKent Overstreet 
344cafe5635SKent Overstreet 	i->version	= BCACHE_BSET_VERSION;
345cafe5635SKent Overstreet 	i->csum		= btree_csum_set(b, i);
346cafe5635SKent Overstreet 
34757943511SKent Overstreet 	BUG_ON(b->bio);
34857943511SKent Overstreet 	b->bio = bch_bbio_alloc(b->c);
34957943511SKent Overstreet 
35057943511SKent Overstreet 	b->bio->bi_end_io	= btree_node_write_endio;
351faadf0c9SKent Overstreet 	b->bio->bi_private	= cl;
3524e1ebae3SColy Li 	b->bio->bi_iter.bi_size	= roundup(set_bytes(i), block_bytes(b->c->cache));
35370fd7614SChristoph Hellwig 	b->bio->bi_opf		= REQ_OP_WRITE | REQ_META | REQ_FUA;
354169ef1cfSKent Overstreet 	bch_bio_map(b->bio, i);
355cafe5635SKent Overstreet 
356e49c7c37SKent Overstreet 	/*
357e49c7c37SKent Overstreet 	 * If we're appending to a leaf node, we don't technically need FUA -
358e49c7c37SKent Overstreet 	 * this write just needs to be persisted before the next journal write,
359e49c7c37SKent Overstreet 	 * which will be marked FLUSH|FUA.
360e49c7c37SKent Overstreet 	 *
361e49c7c37SKent Overstreet 	 * Similarly if we're writing a new btree root - the pointer is going to
362e49c7c37SKent Overstreet 	 * be in the next journal entry.
363e49c7c37SKent Overstreet 	 *
364e49c7c37SKent Overstreet 	 * But if we're writing a new btree node (that isn't a root) or
365e49c7c37SKent Overstreet 	 * appending to a non leaf btree node, we need either FUA or a flush
366e49c7c37SKent Overstreet 	 * when we write the parent with the new pointer. FUA is cheaper than a
367e49c7c37SKent Overstreet 	 * flush, and writes appending to leaf nodes aren't blocking anything so
368e49c7c37SKent Overstreet 	 * just make all btree node writes FUA to keep things sane.
369e49c7c37SKent Overstreet 	 */
370e49c7c37SKent Overstreet 
371cafe5635SKent Overstreet 	bkey_copy(&k.key, &b->key);
372ee811287SKent Overstreet 	SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) +
373a85e968eSKent Overstreet 		       bset_sector_offset(&b->keys, i));
374cafe5635SKent Overstreet 
37525d8be77SMing Lei 	if (!bch_bio_alloc_pages(b->bio, __GFP_NOWARN|GFP_NOWAIT)) {
376cafe5635SKent Overstreet 		struct bio_vec *bv;
377f936b06aSChristoph Hellwig 		void *addr = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
3786dc4f100SMing Lei 		struct bvec_iter_all iter_all;
379cafe5635SKent Overstreet 
3802b070cfeSChristoph Hellwig 		bio_for_each_segment_all(bv, b->bio, iter_all) {
381f936b06aSChristoph Hellwig 			memcpy(page_address(bv->bv_page), addr, PAGE_SIZE);
382f936b06aSChristoph Hellwig 			addr += PAGE_SIZE;
383f936b06aSChristoph Hellwig 		}
384cafe5635SKent Overstreet 
385cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
386cafe5635SKent Overstreet 
38757943511SKent Overstreet 		continue_at(cl, btree_node_write_done, NULL);
388cafe5635SKent Overstreet 	} else {
389b0d30981SColy Li 		/*
390b0d30981SColy Li 		 * No problem for multipage bvec since the bio is
391b0d30981SColy Li 		 * just allocated
392b0d30981SColy Li 		 */
393cafe5635SKent Overstreet 		b->bio->bi_vcnt = 0;
394169ef1cfSKent Overstreet 		bch_bio_map(b->bio, i);
395cafe5635SKent Overstreet 
396cafe5635SKent Overstreet 		bch_submit_bbio(b->bio, b->c, &k.key, 0);
397cafe5635SKent Overstreet 
398cafe5635SKent Overstreet 		closure_sync(cl);
399cb7a583eSKent Overstreet 		continue_at_nobarrier(cl, __btree_node_write_done, NULL);
400cafe5635SKent Overstreet 	}
401cafe5635SKent Overstreet }
402cafe5635SKent Overstreet 
4032a285686SKent Overstreet void __bch_btree_node_write(struct btree *b, struct closure *parent)
404cafe5635SKent Overstreet {
405ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
406cafe5635SKent Overstreet 
4072a285686SKent Overstreet 	lockdep_assert_held(&b->write_lock);
4082a285686SKent Overstreet 
409c37511b8SKent Overstreet 	trace_bcache_btree_write(b);
410c37511b8SKent Overstreet 
411cafe5635SKent Overstreet 	BUG_ON(current->bio_list);
41257943511SKent Overstreet 	BUG_ON(b->written >= btree_blocks(b));
41357943511SKent Overstreet 	BUG_ON(b->written && !i->keys);
414ee811287SKent Overstreet 	BUG_ON(btree_bset_first(b)->seq != i->seq);
415dc9d98d6SKent Overstreet 	bch_check_keys(&b->keys, "writing");
416cafe5635SKent Overstreet 
417cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
418cafe5635SKent Overstreet 
41957943511SKent Overstreet 	/* If caller isn't waiting for write, parent refcount is cache set */
420cb7a583eSKent Overstreet 	down(&b->io_mutex);
421cb7a583eSKent Overstreet 	closure_init(&b->io, parent ?: &b->c->cl);
42257943511SKent Overstreet 
423cafe5635SKent Overstreet 	clear_bit(BTREE_NODE_dirty,	 &b->flags);
424cafe5635SKent Overstreet 	change_bit(BTREE_NODE_write_idx, &b->flags);
425cafe5635SKent Overstreet 
42657943511SKent Overstreet 	do_btree_node_write(b);
427cafe5635SKent Overstreet 
4284a784266SColy Li 	atomic_long_add(set_blocks(i, block_bytes(b->c->cache)) * b->c->cache->sb.block_size,
429cafe5635SKent Overstreet 			&PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
430cafe5635SKent Overstreet 
4314e1ebae3SColy Li 	b->written += set_blocks(i, block_bytes(b->c->cache));
4322a285686SKent Overstreet }
433a85e968eSKent Overstreet 
4342a285686SKent Overstreet void bch_btree_node_write(struct btree *b, struct closure *parent)
4352a285686SKent Overstreet {
4366f10f7d1SColy Li 	unsigned int nsets = b->keys.nsets;
4372a285686SKent Overstreet 
4382a285686SKent Overstreet 	lockdep_assert_held(&b->lock);
4392a285686SKent Overstreet 
4402a285686SKent Overstreet 	__bch_btree_node_write(b, parent);
441cafe5635SKent Overstreet 
44278b77bf8SKent Overstreet 	/*
44378b77bf8SKent Overstreet 	 * do verify if there was more than one set initially (i.e. we did a
44478b77bf8SKent Overstreet 	 * sort) and we sorted down to a single set:
44578b77bf8SKent Overstreet 	 */
4462a285686SKent Overstreet 	if (nsets && !b->keys.nsets)
44778b77bf8SKent Overstreet 		bch_btree_verify(b);
44878b77bf8SKent Overstreet 
4492a285686SKent Overstreet 	bch_btree_init_next(b);
450cafe5635SKent Overstreet }
451cafe5635SKent Overstreet 
452f269af5aSKent Overstreet static void bch_btree_node_write_sync(struct btree *b)
453f269af5aSKent Overstreet {
454f269af5aSKent Overstreet 	struct closure cl;
455f269af5aSKent Overstreet 
456f269af5aSKent Overstreet 	closure_init_stack(&cl);
4572a285686SKent Overstreet 
4582a285686SKent Overstreet 	mutex_lock(&b->write_lock);
459f269af5aSKent Overstreet 	bch_btree_node_write(b, &cl);
4602a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
4612a285686SKent Overstreet 
462f269af5aSKent Overstreet 	closure_sync(&cl);
463f269af5aSKent Overstreet }
464f269af5aSKent Overstreet 
46557943511SKent Overstreet static void btree_node_write_work(struct work_struct *w)
466cafe5635SKent Overstreet {
467cafe5635SKent Overstreet 	struct btree *b = container_of(to_delayed_work(w), struct btree, work);
468cafe5635SKent Overstreet 
4692a285686SKent Overstreet 	mutex_lock(&b->write_lock);
470cafe5635SKent Overstreet 	if (btree_node_dirty(b))
4712a285686SKent Overstreet 		__bch_btree_node_write(b, NULL);
4722a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
473cafe5635SKent Overstreet }
474cafe5635SKent Overstreet 
475c18536a7SKent Overstreet static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
476cafe5635SKent Overstreet {
477ee811287SKent Overstreet 	struct bset *i = btree_bset_last(b);
478cafe5635SKent Overstreet 	struct btree_write *w = btree_current_write(b);
479cafe5635SKent Overstreet 
4802a285686SKent Overstreet 	lockdep_assert_held(&b->write_lock);
4812a285686SKent Overstreet 
48257943511SKent Overstreet 	BUG_ON(!b->written);
48357943511SKent Overstreet 	BUG_ON(!i->keys);
484cafe5635SKent Overstreet 
48557943511SKent Overstreet 	if (!btree_node_dirty(b))
486*9f233ffeSKai Krakow 		queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
48757943511SKent Overstreet 
488cafe5635SKent Overstreet 	set_btree_node_dirty(b);
489cafe5635SKent Overstreet 
4905dccefd3SColy Li 	/*
4915dccefd3SColy Li 	 * w->journal is always the oldest journal pin of all bkeys
4925dccefd3SColy Li 	 * in the leaf node, to make sure the oldest jset seq won't
4935dccefd3SColy Li 	 * be increased before this btree node is flushed.
4945dccefd3SColy Li 	 */
495c18536a7SKent Overstreet 	if (journal_ref) {
496cafe5635SKent Overstreet 		if (w->journal &&
497c18536a7SKent Overstreet 		    journal_pin_cmp(b->c, w->journal, journal_ref)) {
498cafe5635SKent Overstreet 			atomic_dec_bug(w->journal);
499cafe5635SKent Overstreet 			w->journal = NULL;
500cafe5635SKent Overstreet 		}
501cafe5635SKent Overstreet 
502cafe5635SKent Overstreet 		if (!w->journal) {
503c18536a7SKent Overstreet 			w->journal = journal_ref;
504cafe5635SKent Overstreet 			atomic_inc(w->journal);
505cafe5635SKent Overstreet 		}
506cafe5635SKent Overstreet 	}
507cafe5635SKent Overstreet 
508cafe5635SKent Overstreet 	/* Force write if set is too big */
50957943511SKent Overstreet 	if (set_bytes(i) > PAGE_SIZE - 48 &&
51057943511SKent Overstreet 	    !current->bio_list)
51157943511SKent Overstreet 		bch_btree_node_write(b, NULL);
512cafe5635SKent Overstreet }
513cafe5635SKent Overstreet 
514cafe5635SKent Overstreet /*
515cafe5635SKent Overstreet  * Btree in memory cache - allocation/freeing
516cafe5635SKent Overstreet  * mca -> memory cache
517cafe5635SKent Overstreet  */
518cafe5635SKent Overstreet 
5197e59c506SDongsheng Yang #define mca_reserve(c)	(((!IS_ERR_OR_NULL(c->root) && c->root->level) \
520cafe5635SKent Overstreet 			  ? c->root->level : 1) * 8 + 16)
521cafe5635SKent Overstreet #define mca_can_free(c)						\
5220a63b66dSKent Overstreet 	max_t(int, 0, c->btree_cache_used - mca_reserve(c))
523cafe5635SKent Overstreet 
524cafe5635SKent Overstreet static void mca_data_free(struct btree *b)
525cafe5635SKent Overstreet {
526cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
527cafe5635SKent Overstreet 
528a85e968eSKent Overstreet 	bch_btree_keys_free(&b->keys);
529cafe5635SKent Overstreet 
5300a63b66dSKent Overstreet 	b->c->btree_cache_used--;
531ee811287SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freed);
532cafe5635SKent Overstreet }
533cafe5635SKent Overstreet 
534cafe5635SKent Overstreet static void mca_bucket_free(struct btree *b)
535cafe5635SKent Overstreet {
536cafe5635SKent Overstreet 	BUG_ON(btree_node_dirty(b));
537cafe5635SKent Overstreet 
538cafe5635SKent Overstreet 	b->key.ptr[0] = 0;
539cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
540cafe5635SKent Overstreet 	list_move(&b->list, &b->c->btree_cache_freeable);
541cafe5635SKent Overstreet }
542cafe5635SKent Overstreet 
5436f10f7d1SColy Li static unsigned int btree_order(struct bkey *k)
544cafe5635SKent Overstreet {
545cafe5635SKent Overstreet 	return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
546cafe5635SKent Overstreet }
547cafe5635SKent Overstreet 
548cafe5635SKent Overstreet static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
549cafe5635SKent Overstreet {
550a85e968eSKent Overstreet 	if (!bch_btree_keys_alloc(&b->keys,
5516f10f7d1SColy Li 				  max_t(unsigned int,
552cafe5635SKent Overstreet 					ilog2(b->c->btree_pages),
553ee811287SKent Overstreet 					btree_order(k)),
554ee811287SKent Overstreet 				  gfp)) {
5550a63b66dSKent Overstreet 		b->c->btree_cache_used++;
556ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache);
557ee811287SKent Overstreet 	} else {
558ee811287SKent Overstreet 		list_move(&b->list, &b->c->btree_cache_freed);
559ee811287SKent Overstreet 	}
560cafe5635SKent Overstreet }
561cafe5635SKent Overstreet 
562cafe5635SKent Overstreet static struct btree *mca_bucket_alloc(struct cache_set *c,
563cafe5635SKent Overstreet 				      struct bkey *k, gfp_t gfp)
564cafe5635SKent Overstreet {
565bd9026c8SColy Li 	/*
566bd9026c8SColy Li 	 * kzalloc() is necessary here for initialization,
567bd9026c8SColy Li 	 * see code comments in bch_btree_keys_init().
568bd9026c8SColy Li 	 */
569cafe5635SKent Overstreet 	struct btree *b = kzalloc(sizeof(struct btree), gfp);
5701fae7cf0SColy Li 
571cafe5635SKent Overstreet 	if (!b)
572cafe5635SKent Overstreet 		return NULL;
573cafe5635SKent Overstreet 
574cafe5635SKent Overstreet 	init_rwsem(&b->lock);
575cafe5635SKent Overstreet 	lockdep_set_novalidate_class(&b->lock);
5762a285686SKent Overstreet 	mutex_init(&b->write_lock);
5772a285686SKent Overstreet 	lockdep_set_novalidate_class(&b->write_lock);
578cafe5635SKent Overstreet 	INIT_LIST_HEAD(&b->list);
57957943511SKent Overstreet 	INIT_DELAYED_WORK(&b->work, btree_node_write_work);
580cafe5635SKent Overstreet 	b->c = c;
581cb7a583eSKent Overstreet 	sema_init(&b->io_mutex, 1);
582cafe5635SKent Overstreet 
583cafe5635SKent Overstreet 	mca_data_alloc(b, k, gfp);
584cafe5635SKent Overstreet 	return b;
585cafe5635SKent Overstreet }
586cafe5635SKent Overstreet 
5876f10f7d1SColy Li static int mca_reap(struct btree *b, unsigned int min_order, bool flush)
588cafe5635SKent Overstreet {
589e8e1d468SKent Overstreet 	struct closure cl;
590e8e1d468SKent Overstreet 
591e8e1d468SKent Overstreet 	closure_init_stack(&cl);
592cafe5635SKent Overstreet 	lockdep_assert_held(&b->c->bucket_lock);
593cafe5635SKent Overstreet 
594cafe5635SKent Overstreet 	if (!down_write_trylock(&b->lock))
595cafe5635SKent Overstreet 		return -ENOMEM;
596cafe5635SKent Overstreet 
597a85e968eSKent Overstreet 	BUG_ON(btree_node_dirty(b) && !b->keys.set[0].data);
598e8e1d468SKent Overstreet 
599a85e968eSKent Overstreet 	if (b->keys.page_order < min_order)
600cb7a583eSKent Overstreet 		goto out_unlock;
601cb7a583eSKent Overstreet 
602cb7a583eSKent Overstreet 	if (!flush) {
603cb7a583eSKent Overstreet 		if (btree_node_dirty(b))
604cb7a583eSKent Overstreet 			goto out_unlock;
605cb7a583eSKent Overstreet 
606cb7a583eSKent Overstreet 		if (down_trylock(&b->io_mutex))
607cb7a583eSKent Overstreet 			goto out_unlock;
608cb7a583eSKent Overstreet 		up(&b->io_mutex);
609cafe5635SKent Overstreet 	}
610cafe5635SKent Overstreet 
61150a260e8SColy Li retry:
61241508bb7SColy Li 	/*
61341508bb7SColy Li 	 * BTREE_NODE_dirty might be cleared in btree_flush_btree() by
61441508bb7SColy Li 	 * __bch_btree_node_write(). To avoid an extra flush, acquire
61541508bb7SColy Li 	 * b->write_lock before checking BTREE_NODE_dirty bit.
61641508bb7SColy Li 	 */
6172a285686SKent Overstreet 	mutex_lock(&b->write_lock);
61850a260e8SColy Li 	/*
61950a260e8SColy Li 	 * If this btree node is selected in btree_flush_write() by journal
62050a260e8SColy Li 	 * code, delay and retry until the node is flushed by journal code
62150a260e8SColy Li 	 * and BTREE_NODE_journal_flush bit cleared by btree_flush_write().
62250a260e8SColy Li 	 */
62350a260e8SColy Li 	if (btree_node_journal_flush(b)) {
62446f5aa88SJoe Perches 		pr_debug("bnode %p is flushing by journal, retry\n", b);
62550a260e8SColy Li 		mutex_unlock(&b->write_lock);
62650a260e8SColy Li 		udelay(1);
62750a260e8SColy Li 		goto retry;
62850a260e8SColy Li 	}
62950a260e8SColy Li 
630f269af5aSKent Overstreet 	if (btree_node_dirty(b))
6312a285686SKent Overstreet 		__bch_btree_node_write(b, &cl);
6322a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
6332a285686SKent Overstreet 
6342a285686SKent Overstreet 	closure_sync(&cl);
635cafe5635SKent Overstreet 
636e8e1d468SKent Overstreet 	/* wait for any in flight btree write */
637cb7a583eSKent Overstreet 	down(&b->io_mutex);
638cb7a583eSKent Overstreet 	up(&b->io_mutex);
639e8e1d468SKent Overstreet 
640cafe5635SKent Overstreet 	return 0;
641cb7a583eSKent Overstreet out_unlock:
642cb7a583eSKent Overstreet 	rw_unlock(true, b);
643cb7a583eSKent Overstreet 	return -ENOMEM;
644cafe5635SKent Overstreet }
645cafe5635SKent Overstreet 
6467dc19d5aSDave Chinner static unsigned long bch_mca_scan(struct shrinker *shrink,
6477dc19d5aSDave Chinner 				  struct shrink_control *sc)
648cafe5635SKent Overstreet {
649cafe5635SKent Overstreet 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
650cafe5635SKent Overstreet 	struct btree *b, *t;
651cafe5635SKent Overstreet 	unsigned long i, nr = sc->nr_to_scan;
6527dc19d5aSDave Chinner 	unsigned long freed = 0;
653ca71df31STang Junhui 	unsigned int btree_cache_used;
654cafe5635SKent Overstreet 
655cafe5635SKent Overstreet 	if (c->shrinker_disabled)
6567dc19d5aSDave Chinner 		return SHRINK_STOP;
657cafe5635SKent Overstreet 
6580a63b66dSKent Overstreet 	if (c->btree_cache_alloc_lock)
6597dc19d5aSDave Chinner 		return SHRINK_STOP;
660cafe5635SKent Overstreet 
661cafe5635SKent Overstreet 	/* Return -1 if we can't do anything right now */
662a698e08cSKent Overstreet 	if (sc->gfp_mask & __GFP_IO)
663cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
664cafe5635SKent Overstreet 	else if (!mutex_trylock(&c->bucket_lock))
665cafe5635SKent Overstreet 		return -1;
666cafe5635SKent Overstreet 
66736c9ea98SKent Overstreet 	/*
66836c9ea98SKent Overstreet 	 * It's _really_ critical that we don't free too many btree nodes - we
66936c9ea98SKent Overstreet 	 * have to always leave ourselves a reserve. The reserve is how we
67036c9ea98SKent Overstreet 	 * guarantee that allocating memory for a new btree node can always
67136c9ea98SKent Overstreet 	 * succeed, so that inserting keys into the btree can always succeed and
67236c9ea98SKent Overstreet 	 * IO can always make forward progress:
67336c9ea98SKent Overstreet 	 */
674cafe5635SKent Overstreet 	nr /= c->btree_pages;
6759fcc34b1SColy Li 	if (nr == 0)
6769fcc34b1SColy Li 		nr = 1;
677cafe5635SKent Overstreet 	nr = min_t(unsigned long, nr, mca_can_free(c));
678cafe5635SKent Overstreet 
679cafe5635SKent Overstreet 	i = 0;
680ca71df31STang Junhui 	btree_cache_used = c->btree_cache_used;
681d5c9c470SColy Li 	list_for_each_entry_safe_reverse(b, t, &c->btree_cache_freeable, list) {
682ca71df31STang Junhui 		if (nr <= 0)
683ca71df31STang Junhui 			goto out;
684cafe5635SKent Overstreet 
685d5c9c470SColy Li 		if (!mca_reap(b, 0, false)) {
686cafe5635SKent Overstreet 			mca_data_free(b);
687cafe5635SKent Overstreet 			rw_unlock(true, b);
6887dc19d5aSDave Chinner 			freed++;
689cafe5635SKent Overstreet 		}
690ca71df31STang Junhui 		nr--;
691d5c9c470SColy Li 		i++;
692cafe5635SKent Overstreet 	}
693cafe5635SKent Overstreet 
694e3de0446SColy Li 	list_for_each_entry_safe_reverse(b, t, &c->btree_cache, list) {
695e3de0446SColy Li 		if (nr <= 0 || i >= btree_cache_used)
696cafe5635SKent Overstreet 			goto out;
697cafe5635SKent Overstreet 
698125d98edSColy Li 		if (!mca_reap(b, 0, false)) {
699cafe5635SKent Overstreet 			mca_bucket_free(b);
700cafe5635SKent Overstreet 			mca_data_free(b);
701cafe5635SKent Overstreet 			rw_unlock(true, b);
7027dc19d5aSDave Chinner 			freed++;
703125d98edSColy Li 		}
704e3de0446SColy Li 
705e3de0446SColy Li 		nr--;
706e3de0446SColy Li 		i++;
707cafe5635SKent Overstreet 	}
708cafe5635SKent Overstreet out:
709cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
710f3641c3aSTang Junhui 	return freed * c->btree_pages;
7117dc19d5aSDave Chinner }
7127dc19d5aSDave Chinner 
7137dc19d5aSDave Chinner static unsigned long bch_mca_count(struct shrinker *shrink,
7147dc19d5aSDave Chinner 				   struct shrink_control *sc)
7157dc19d5aSDave Chinner {
7167dc19d5aSDave Chinner 	struct cache_set *c = container_of(shrink, struct cache_set, shrink);
7177dc19d5aSDave Chinner 
7187dc19d5aSDave Chinner 	if (c->shrinker_disabled)
7197dc19d5aSDave Chinner 		return 0;
7207dc19d5aSDave Chinner 
7210a63b66dSKent Overstreet 	if (c->btree_cache_alloc_lock)
7227dc19d5aSDave Chinner 		return 0;
7237dc19d5aSDave Chinner 
7247dc19d5aSDave Chinner 	return mca_can_free(c) * c->btree_pages;
725cafe5635SKent Overstreet }
726cafe5635SKent Overstreet 
727cafe5635SKent Overstreet void bch_btree_cache_free(struct cache_set *c)
728cafe5635SKent Overstreet {
729cafe5635SKent Overstreet 	struct btree *b;
730cafe5635SKent Overstreet 	struct closure cl;
7311fae7cf0SColy Li 
732cafe5635SKent Overstreet 	closure_init_stack(&cl);
733cafe5635SKent Overstreet 
734cafe5635SKent Overstreet 	if (c->shrink.list.next)
735cafe5635SKent Overstreet 		unregister_shrinker(&c->shrink);
736cafe5635SKent Overstreet 
737cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
738cafe5635SKent Overstreet 
739cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
740cafe5635SKent Overstreet 	if (c->verify_data)
741cafe5635SKent Overstreet 		list_move(&c->verify_data->list, &c->btree_cache);
74278b77bf8SKent Overstreet 
7434a784266SColy Li 	free_pages((unsigned long) c->verify_ondisk, ilog2(meta_bucket_pages(&c->cache->sb)));
744cafe5635SKent Overstreet #endif
745cafe5635SKent Overstreet 
746cafe5635SKent Overstreet 	list_splice(&c->btree_cache_freeable,
747cafe5635SKent Overstreet 		    &c->btree_cache);
748cafe5635SKent Overstreet 
749cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache)) {
750cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache, struct btree, list);
751cafe5635SKent Overstreet 
75241508bb7SColy Li 		/*
75341508bb7SColy Li 		 * This function is called by cache_set_free(), no I/O
75441508bb7SColy Li 		 * request on cache now, it is unnecessary to acquire
75541508bb7SColy Li 		 * b->write_lock before clearing BTREE_NODE_dirty anymore.
75641508bb7SColy Li 		 */
757e5ec5f47SColy Li 		if (btree_node_dirty(b)) {
758cafe5635SKent Overstreet 			btree_complete_write(b, btree_current_write(b));
759cafe5635SKent Overstreet 			clear_bit(BTREE_NODE_dirty, &b->flags);
760e5ec5f47SColy Li 		}
761cafe5635SKent Overstreet 		mca_data_free(b);
762cafe5635SKent Overstreet 	}
763cafe5635SKent Overstreet 
764cafe5635SKent Overstreet 	while (!list_empty(&c->btree_cache_freed)) {
765cafe5635SKent Overstreet 		b = list_first_entry(&c->btree_cache_freed,
766cafe5635SKent Overstreet 				     struct btree, list);
767cafe5635SKent Overstreet 		list_del(&b->list);
768cafe5635SKent Overstreet 		cancel_delayed_work_sync(&b->work);
769cafe5635SKent Overstreet 		kfree(b);
770cafe5635SKent Overstreet 	}
771cafe5635SKent Overstreet 
772cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
773cafe5635SKent Overstreet }
774cafe5635SKent Overstreet 
775cafe5635SKent Overstreet int bch_btree_cache_alloc(struct cache_set *c)
776cafe5635SKent Overstreet {
7776f10f7d1SColy Li 	unsigned int i;
778cafe5635SKent Overstreet 
779cafe5635SKent Overstreet 	for (i = 0; i < mca_reserve(c); i++)
78072a44517SKent Overstreet 		if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
78172a44517SKent Overstreet 			return -ENOMEM;
782cafe5635SKent Overstreet 
783cafe5635SKent Overstreet 	list_splice_init(&c->btree_cache,
784cafe5635SKent Overstreet 			 &c->btree_cache_freeable);
785cafe5635SKent Overstreet 
786cafe5635SKent Overstreet #ifdef CONFIG_BCACHE_DEBUG
787cafe5635SKent Overstreet 	mutex_init(&c->verify_lock);
788cafe5635SKent Overstreet 
78978b77bf8SKent Overstreet 	c->verify_ondisk = (void *)
7904a784266SColy Li 		__get_free_pages(GFP_KERNEL|__GFP_COMP,
7914a784266SColy Li 				 ilog2(meta_bucket_pages(&c->cache->sb)));
792bf6af170SColy Li 	if (!c->verify_ondisk) {
793bf6af170SColy Li 		/*
794bf6af170SColy Li 		 * Don't worry about the mca_rereserve buckets
795bf6af170SColy Li 		 * allocated in previous for-loop, they will be
796bf6af170SColy Li 		 * handled properly in bch_cache_set_unregister().
797bf6af170SColy Li 		 */
798bf6af170SColy Li 		return -ENOMEM;
799bf6af170SColy Li 	}
80078b77bf8SKent Overstreet 
801cafe5635SKent Overstreet 	c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
802cafe5635SKent Overstreet 
803cafe5635SKent Overstreet 	if (c->verify_data &&
804a85e968eSKent Overstreet 	    c->verify_data->keys.set->data)
805cafe5635SKent Overstreet 		list_del_init(&c->verify_data->list);
806cafe5635SKent Overstreet 	else
807cafe5635SKent Overstreet 		c->verify_data = NULL;
808cafe5635SKent Overstreet #endif
809cafe5635SKent Overstreet 
8107dc19d5aSDave Chinner 	c->shrink.count_objects = bch_mca_count;
8117dc19d5aSDave Chinner 	c->shrink.scan_objects = bch_mca_scan;
812cafe5635SKent Overstreet 	c->shrink.seeks = 4;
813cafe5635SKent Overstreet 	c->shrink.batch = c->btree_pages * 2;
8146c4ca1e3SMichael Lyle 
8156c4ca1e3SMichael Lyle 	if (register_shrinker(&c->shrink))
81646f5aa88SJoe Perches 		pr_warn("bcache: %s: could not register shrinker\n",
8176c4ca1e3SMichael Lyle 				__func__);
818cafe5635SKent Overstreet 
819cafe5635SKent Overstreet 	return 0;
820cafe5635SKent Overstreet }
821cafe5635SKent Overstreet 
822cafe5635SKent Overstreet /* Btree in memory cache - hash table */
823cafe5635SKent Overstreet 
824cafe5635SKent Overstreet static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
825cafe5635SKent Overstreet {
826cafe5635SKent Overstreet 	return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
827cafe5635SKent Overstreet }
828cafe5635SKent Overstreet 
829cafe5635SKent Overstreet static struct btree *mca_find(struct cache_set *c, struct bkey *k)
830cafe5635SKent Overstreet {
831cafe5635SKent Overstreet 	struct btree *b;
832cafe5635SKent Overstreet 
833cafe5635SKent Overstreet 	rcu_read_lock();
834cafe5635SKent Overstreet 	hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
835cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
836cafe5635SKent Overstreet 			goto out;
837cafe5635SKent Overstreet 	b = NULL;
838cafe5635SKent Overstreet out:
839cafe5635SKent Overstreet 	rcu_read_unlock();
840cafe5635SKent Overstreet 	return b;
841cafe5635SKent Overstreet }
842cafe5635SKent Overstreet 
8430a63b66dSKent Overstreet static int mca_cannibalize_lock(struct cache_set *c, struct btree_op *op)
8440a63b66dSKent Overstreet {
84534cf78bfSGuoju Fang 	spin_lock(&c->btree_cannibalize_lock);
84634cf78bfSGuoju Fang 	if (likely(c->btree_cache_alloc_lock == NULL)) {
84734cf78bfSGuoju Fang 		c->btree_cache_alloc_lock = current;
84834cf78bfSGuoju Fang 	} else if (c->btree_cache_alloc_lock != current) {
8490a63b66dSKent Overstreet 		if (op)
8500a63b66dSKent Overstreet 			prepare_to_wait(&c->btree_cache_wait, &op->wait,
8510a63b66dSKent Overstreet 					TASK_UNINTERRUPTIBLE);
85234cf78bfSGuoju Fang 		spin_unlock(&c->btree_cannibalize_lock);
8530a63b66dSKent Overstreet 		return -EINTR;
8540a63b66dSKent Overstreet 	}
85534cf78bfSGuoju Fang 	spin_unlock(&c->btree_cannibalize_lock);
8560a63b66dSKent Overstreet 
8570a63b66dSKent Overstreet 	return 0;
8580a63b66dSKent Overstreet }
8590a63b66dSKent Overstreet 
8600a63b66dSKent Overstreet static struct btree *mca_cannibalize(struct cache_set *c, struct btree_op *op,
8610a63b66dSKent Overstreet 				     struct bkey *k)
862cafe5635SKent Overstreet {
863e8e1d468SKent Overstreet 	struct btree *b;
864cafe5635SKent Overstreet 
865c37511b8SKent Overstreet 	trace_bcache_btree_cache_cannibalize(c);
866c37511b8SKent Overstreet 
8670a63b66dSKent Overstreet 	if (mca_cannibalize_lock(c, op))
8680a63b66dSKent Overstreet 		return ERR_PTR(-EINTR);
869cafe5635SKent Overstreet 
870e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
871e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
872e8e1d468SKent Overstreet 			return b;
873cafe5635SKent Overstreet 
874e8e1d468SKent Overstreet 	list_for_each_entry_reverse(b, &c->btree_cache, list)
875e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), true))
876e8e1d468SKent Overstreet 			return b;
877e8e1d468SKent Overstreet 
8780a63b66dSKent Overstreet 	WARN(1, "btree cache cannibalize failed\n");
879e8e1d468SKent Overstreet 	return ERR_PTR(-ENOMEM);
880cafe5635SKent Overstreet }
881cafe5635SKent Overstreet 
882cafe5635SKent Overstreet /*
883cafe5635SKent Overstreet  * We can only have one thread cannibalizing other cached btree nodes at a time,
884cafe5635SKent Overstreet  * or we'll deadlock. We use an open coded mutex to ensure that, which a
885cafe5635SKent Overstreet  * cannibalize_bucket() will take. This means every time we unlock the root of
886cafe5635SKent Overstreet  * the btree, we need to release this lock if we have it held.
887cafe5635SKent Overstreet  */
888df8e8970SKent Overstreet static void bch_cannibalize_unlock(struct cache_set *c)
889cafe5635SKent Overstreet {
89034cf78bfSGuoju Fang 	spin_lock(&c->btree_cannibalize_lock);
8910a63b66dSKent Overstreet 	if (c->btree_cache_alloc_lock == current) {
8920a63b66dSKent Overstreet 		c->btree_cache_alloc_lock = NULL;
8930a63b66dSKent Overstreet 		wake_up(&c->btree_cache_wait);
894cafe5635SKent Overstreet 	}
89534cf78bfSGuoju Fang 	spin_unlock(&c->btree_cannibalize_lock);
896cafe5635SKent Overstreet }
897cafe5635SKent Overstreet 
8980a63b66dSKent Overstreet static struct btree *mca_alloc(struct cache_set *c, struct btree_op *op,
8990a63b66dSKent Overstreet 			       struct bkey *k, int level)
900cafe5635SKent Overstreet {
901cafe5635SKent Overstreet 	struct btree *b;
902cafe5635SKent Overstreet 
903e8e1d468SKent Overstreet 	BUG_ON(current->bio_list);
904e8e1d468SKent Overstreet 
905cafe5635SKent Overstreet 	lockdep_assert_held(&c->bucket_lock);
906cafe5635SKent Overstreet 
907cafe5635SKent Overstreet 	if (mca_find(c, k))
908cafe5635SKent Overstreet 		return NULL;
909cafe5635SKent Overstreet 
910cafe5635SKent Overstreet 	/* btree_free() doesn't free memory; it sticks the node on the end of
911cafe5635SKent Overstreet 	 * the list. Check if there's any freed nodes there:
912cafe5635SKent Overstreet 	 */
913cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freeable, list)
914e8e1d468SKent Overstreet 		if (!mca_reap(b, btree_order(k), false))
915cafe5635SKent Overstreet 			goto out;
916cafe5635SKent Overstreet 
917cafe5635SKent Overstreet 	/* We never free struct btree itself, just the memory that holds the on
918cafe5635SKent Overstreet 	 * disk node. Check the freed list before allocating a new one:
919cafe5635SKent Overstreet 	 */
920cafe5635SKent Overstreet 	list_for_each_entry(b, &c->btree_cache_freed, list)
921e8e1d468SKent Overstreet 		if (!mca_reap(b, 0, false)) {
922cafe5635SKent Overstreet 			mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
923a85e968eSKent Overstreet 			if (!b->keys.set[0].data)
924cafe5635SKent Overstreet 				goto err;
925cafe5635SKent Overstreet 			else
926cafe5635SKent Overstreet 				goto out;
927cafe5635SKent Overstreet 		}
928cafe5635SKent Overstreet 
929cafe5635SKent Overstreet 	b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
930cafe5635SKent Overstreet 	if (!b)
931cafe5635SKent Overstreet 		goto err;
932cafe5635SKent Overstreet 
933cafe5635SKent Overstreet 	BUG_ON(!down_write_trylock(&b->lock));
934a85e968eSKent Overstreet 	if (!b->keys.set->data)
935cafe5635SKent Overstreet 		goto err;
936cafe5635SKent Overstreet out:
937cb7a583eSKent Overstreet 	BUG_ON(b->io_mutex.count != 1);
938cafe5635SKent Overstreet 
939cafe5635SKent Overstreet 	bkey_copy(&b->key, k);
940cafe5635SKent Overstreet 	list_move(&b->list, &c->btree_cache);
941cafe5635SKent Overstreet 	hlist_del_init_rcu(&b->hash);
942cafe5635SKent Overstreet 	hlist_add_head_rcu(&b->hash, mca_hash(c, k));
943cafe5635SKent Overstreet 
944cafe5635SKent Overstreet 	lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
945d6fd3b11SKent Overstreet 	b->parent	= (void *) ~0UL;
946a85e968eSKent Overstreet 	b->flags	= 0;
947a85e968eSKent Overstreet 	b->written	= 0;
948a85e968eSKent Overstreet 	b->level	= level;
949cafe5635SKent Overstreet 
95065d45231SKent Overstreet 	if (!b->level)
951a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_extent_keys_ops,
952a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
95365d45231SKent Overstreet 	else
954a85e968eSKent Overstreet 		bch_btree_keys_init(&b->keys, &bch_btree_keys_ops,
955a85e968eSKent Overstreet 				    &b->c->expensive_debug_checks);
956cafe5635SKent Overstreet 
957cafe5635SKent Overstreet 	return b;
958cafe5635SKent Overstreet err:
959cafe5635SKent Overstreet 	if (b)
960cafe5635SKent Overstreet 		rw_unlock(true, b);
961cafe5635SKent Overstreet 
9620a63b66dSKent Overstreet 	b = mca_cannibalize(c, op, k);
963cafe5635SKent Overstreet 	if (!IS_ERR(b))
964cafe5635SKent Overstreet 		goto out;
965cafe5635SKent Overstreet 
966cafe5635SKent Overstreet 	return b;
967cafe5635SKent Overstreet }
968cafe5635SKent Overstreet 
96947344e33SBart Van Assche /*
970cafe5635SKent Overstreet  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
971cafe5635SKent Overstreet  * in from disk if necessary.
972cafe5635SKent Overstreet  *
973ed00aabdSChristoph Hellwig  * If IO is necessary and running under submit_bio_noacct, returns -EAGAIN.
974cafe5635SKent Overstreet  *
975cafe5635SKent Overstreet  * The btree node will have either a read or a write lock held, depending on
976cafe5635SKent Overstreet  * level and op->lock.
977cafe5635SKent Overstreet  */
9780a63b66dSKent Overstreet struct btree *bch_btree_node_get(struct cache_set *c, struct btree_op *op,
9792452cc89SSlava Pestov 				 struct bkey *k, int level, bool write,
9802452cc89SSlava Pestov 				 struct btree *parent)
981cafe5635SKent Overstreet {
982cafe5635SKent Overstreet 	int i = 0;
983cafe5635SKent Overstreet 	struct btree *b;
984cafe5635SKent Overstreet 
985cafe5635SKent Overstreet 	BUG_ON(level < 0);
986cafe5635SKent Overstreet retry:
987cafe5635SKent Overstreet 	b = mca_find(c, k);
988cafe5635SKent Overstreet 
989cafe5635SKent Overstreet 	if (!b) {
99057943511SKent Overstreet 		if (current->bio_list)
99157943511SKent Overstreet 			return ERR_PTR(-EAGAIN);
99257943511SKent Overstreet 
993cafe5635SKent Overstreet 		mutex_lock(&c->bucket_lock);
9940a63b66dSKent Overstreet 		b = mca_alloc(c, op, k, level);
995cafe5635SKent Overstreet 		mutex_unlock(&c->bucket_lock);
996cafe5635SKent Overstreet 
997cafe5635SKent Overstreet 		if (!b)
998cafe5635SKent Overstreet 			goto retry;
999cafe5635SKent Overstreet 		if (IS_ERR(b))
1000cafe5635SKent Overstreet 			return b;
1001cafe5635SKent Overstreet 
100257943511SKent Overstreet 		bch_btree_node_read(b);
1003cafe5635SKent Overstreet 
1004cafe5635SKent Overstreet 		if (!write)
1005cafe5635SKent Overstreet 			downgrade_write(&b->lock);
1006cafe5635SKent Overstreet 	} else {
1007cafe5635SKent Overstreet 		rw_lock(write, b, level);
1008cafe5635SKent Overstreet 		if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
1009cafe5635SKent Overstreet 			rw_unlock(write, b);
1010cafe5635SKent Overstreet 			goto retry;
1011cafe5635SKent Overstreet 		}
1012cafe5635SKent Overstreet 		BUG_ON(b->level != level);
1013cafe5635SKent Overstreet 	}
1014cafe5635SKent Overstreet 
1015c2e8dcf7SColy Li 	if (btree_node_io_error(b)) {
1016c2e8dcf7SColy Li 		rw_unlock(write, b);
1017c2e8dcf7SColy Li 		return ERR_PTR(-EIO);
1018c2e8dcf7SColy Li 	}
1019c2e8dcf7SColy Li 
1020c2e8dcf7SColy Li 	BUG_ON(!b->written);
1021c2e8dcf7SColy Li 
10222452cc89SSlava Pestov 	b->parent = parent;
1023cafe5635SKent Overstreet 
1024a85e968eSKent Overstreet 	for (; i <= b->keys.nsets && b->keys.set[i].size; i++) {
1025a85e968eSKent Overstreet 		prefetch(b->keys.set[i].tree);
1026a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
1027cafe5635SKent Overstreet 	}
1028cafe5635SKent Overstreet 
1029a85e968eSKent Overstreet 	for (; i <= b->keys.nsets; i++)
1030a85e968eSKent Overstreet 		prefetch(b->keys.set[i].data);
1031cafe5635SKent Overstreet 
1032cafe5635SKent Overstreet 	return b;
1033cafe5635SKent Overstreet }
1034cafe5635SKent Overstreet 
10352452cc89SSlava Pestov static void btree_node_prefetch(struct btree *parent, struct bkey *k)
1036cafe5635SKent Overstreet {
1037cafe5635SKent Overstreet 	struct btree *b;
1038cafe5635SKent Overstreet 
10392452cc89SSlava Pestov 	mutex_lock(&parent->c->bucket_lock);
10402452cc89SSlava Pestov 	b = mca_alloc(parent->c, NULL, k, parent->level - 1);
10412452cc89SSlava Pestov 	mutex_unlock(&parent->c->bucket_lock);
1042cafe5635SKent Overstreet 
1043cafe5635SKent Overstreet 	if (!IS_ERR_OR_NULL(b)) {
10442452cc89SSlava Pestov 		b->parent = parent;
104557943511SKent Overstreet 		bch_btree_node_read(b);
1046cafe5635SKent Overstreet 		rw_unlock(true, b);
1047cafe5635SKent Overstreet 	}
1048cafe5635SKent Overstreet }
1049cafe5635SKent Overstreet 
1050cafe5635SKent Overstreet /* Btree alloc */
1051cafe5635SKent Overstreet 
1052e8e1d468SKent Overstreet static void btree_node_free(struct btree *b)
1053cafe5635SKent Overstreet {
1054c37511b8SKent Overstreet 	trace_bcache_btree_node_free(b);
1055c37511b8SKent Overstreet 
1056cafe5635SKent Overstreet 	BUG_ON(b == b->c->root);
1057cafe5635SKent Overstreet 
105850a260e8SColy Li retry:
10592a285686SKent Overstreet 	mutex_lock(&b->write_lock);
106050a260e8SColy Li 	/*
106150a260e8SColy Li 	 * If the btree node is selected and flushing in btree_flush_write(),
106250a260e8SColy Li 	 * delay and retry until the BTREE_NODE_journal_flush bit cleared,
106350a260e8SColy Li 	 * then it is safe to free the btree node here. Otherwise this btree
106450a260e8SColy Li 	 * node will be in race condition.
106550a260e8SColy Li 	 */
106650a260e8SColy Li 	if (btree_node_journal_flush(b)) {
106750a260e8SColy Li 		mutex_unlock(&b->write_lock);
106846f5aa88SJoe Perches 		pr_debug("bnode %p journal_flush set, retry\n", b);
106950a260e8SColy Li 		udelay(1);
107050a260e8SColy Li 		goto retry;
107150a260e8SColy Li 	}
10722a285686SKent Overstreet 
1073e5ec5f47SColy Li 	if (btree_node_dirty(b)) {
1074cafe5635SKent Overstreet 		btree_complete_write(b, btree_current_write(b));
1075cafe5635SKent Overstreet 		clear_bit(BTREE_NODE_dirty, &b->flags);
1076e5ec5f47SColy Li 	}
1077cafe5635SKent Overstreet 
10782a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
10792a285686SKent Overstreet 
1080cafe5635SKent Overstreet 	cancel_delayed_work(&b->work);
1081cafe5635SKent Overstreet 
1082cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
1083cafe5635SKent Overstreet 	bch_bucket_free(b->c, &b->key);
1084cafe5635SKent Overstreet 	mca_bucket_free(b);
1085cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
1086cafe5635SKent Overstreet }
1087cafe5635SKent Overstreet 
1088c5aa4a31SSlava Pestov struct btree *__bch_btree_node_alloc(struct cache_set *c, struct btree_op *op,
10892452cc89SSlava Pestov 				     int level, bool wait,
10902452cc89SSlava Pestov 				     struct btree *parent)
1091cafe5635SKent Overstreet {
1092cafe5635SKent Overstreet 	BKEY_PADDED(key) k;
1093cafe5635SKent Overstreet 	struct btree *b = ERR_PTR(-EAGAIN);
1094cafe5635SKent Overstreet 
1095cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1096cafe5635SKent Overstreet retry:
109717e4aed8SColy Li 	if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, wait))
1098cafe5635SKent Overstreet 		goto err;
1099cafe5635SKent Overstreet 
11003a3b6a4eSKent Overstreet 	bkey_put(c, &k.key);
1101cafe5635SKent Overstreet 	SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1102cafe5635SKent Overstreet 
11030a63b66dSKent Overstreet 	b = mca_alloc(c, op, &k.key, level);
1104cafe5635SKent Overstreet 	if (IS_ERR(b))
1105cafe5635SKent Overstreet 		goto err_free;
1106cafe5635SKent Overstreet 
1107cafe5635SKent Overstreet 	if (!b) {
1108b1a67b0fSKent Overstreet 		cache_bug(c,
1109b1a67b0fSKent Overstreet 			"Tried to allocate bucket that was in btree cache");
1110cafe5635SKent Overstreet 		goto retry;
1111cafe5635SKent Overstreet 	}
1112cafe5635SKent Overstreet 
11132452cc89SSlava Pestov 	b->parent = parent;
11144a784266SColy Li 	bch_bset_init_next(&b->keys, b->keys.set->data, bset_magic(&b->c->cache->sb));
1115cafe5635SKent Overstreet 
1116cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1117c37511b8SKent Overstreet 
1118c37511b8SKent Overstreet 	trace_bcache_btree_node_alloc(b);
1119cafe5635SKent Overstreet 	return b;
1120cafe5635SKent Overstreet err_free:
1121cafe5635SKent Overstreet 	bch_bucket_free(c, &k.key);
1122cafe5635SKent Overstreet err:
1123cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1124c37511b8SKent Overstreet 
1125913dc33fSSlava Pestov 	trace_bcache_btree_node_alloc_fail(c);
1126cafe5635SKent Overstreet 	return b;
1127cafe5635SKent Overstreet }
1128cafe5635SKent Overstreet 
1129c5aa4a31SSlava Pestov static struct btree *bch_btree_node_alloc(struct cache_set *c,
11302452cc89SSlava Pestov 					  struct btree_op *op, int level,
11312452cc89SSlava Pestov 					  struct btree *parent)
1132c5aa4a31SSlava Pestov {
11332452cc89SSlava Pestov 	return __bch_btree_node_alloc(c, op, level, op != NULL, parent);
1134c5aa4a31SSlava Pestov }
1135c5aa4a31SSlava Pestov 
11360a63b66dSKent Overstreet static struct btree *btree_node_alloc_replacement(struct btree *b,
11370a63b66dSKent Overstreet 						  struct btree_op *op)
1138cafe5635SKent Overstreet {
11392452cc89SSlava Pestov 	struct btree *n = bch_btree_node_alloc(b->c, op, b->level, b->parent);
11401fae7cf0SColy Li 
114167539e85SKent Overstreet 	if (!IS_ERR_OR_NULL(n)) {
11422a285686SKent Overstreet 		mutex_lock(&n->write_lock);
114389ebb4a2SKent Overstreet 		bch_btree_sort_into(&b->keys, &n->keys, &b->c->sort);
114467539e85SKent Overstreet 		bkey_copy_key(&n->key, &b->key);
11452a285686SKent Overstreet 		mutex_unlock(&n->write_lock);
114667539e85SKent Overstreet 	}
1147cafe5635SKent Overstreet 
1148cafe5635SKent Overstreet 	return n;
1149cafe5635SKent Overstreet }
1150cafe5635SKent Overstreet 
11518835c123SKent Overstreet static void make_btree_freeing_key(struct btree *b, struct bkey *k)
11528835c123SKent Overstreet {
11536f10f7d1SColy Li 	unsigned int i;
11548835c123SKent Overstreet 
115505335cffSKent Overstreet 	mutex_lock(&b->c->bucket_lock);
115605335cffSKent Overstreet 
115705335cffSKent Overstreet 	atomic_inc(&b->c->prio_blocked);
115805335cffSKent Overstreet 
11598835c123SKent Overstreet 	bkey_copy(k, &b->key);
11608835c123SKent Overstreet 	bkey_copy_key(k, &ZERO_KEY);
11618835c123SKent Overstreet 
116205335cffSKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
116305335cffSKent Overstreet 		SET_PTR_GEN(k, i,
116405335cffSKent Overstreet 			    bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
116505335cffSKent Overstreet 					PTR_BUCKET(b->c, &b->key, i)));
11668835c123SKent Overstreet 
116705335cffSKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
11688835c123SKent Overstreet }
11698835c123SKent Overstreet 
117078365411SKent Overstreet static int btree_check_reserve(struct btree *b, struct btree_op *op)
117178365411SKent Overstreet {
117278365411SKent Overstreet 	struct cache_set *c = b->c;
117308fdb2cdSColy Li 	struct cache *ca = c->cache;
117408fdb2cdSColy Li 	unsigned int reserve = (c->root->level - b->level) * 2 + 1;
117578365411SKent Overstreet 
117678365411SKent Overstreet 	mutex_lock(&c->bucket_lock);
117778365411SKent Overstreet 
117878365411SKent Overstreet 	if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
117978365411SKent Overstreet 		if (op)
11800a63b66dSKent Overstreet 			prepare_to_wait(&c->btree_cache_wait, &op->wait,
118178365411SKent Overstreet 					TASK_UNINTERRUPTIBLE);
11820a63b66dSKent Overstreet 		mutex_unlock(&c->bucket_lock);
11830a63b66dSKent Overstreet 		return -EINTR;
118478365411SKent Overstreet 	}
118578365411SKent Overstreet 
118678365411SKent Overstreet 	mutex_unlock(&c->bucket_lock);
11870a63b66dSKent Overstreet 
11880a63b66dSKent Overstreet 	return mca_cannibalize_lock(b->c, op);
118978365411SKent Overstreet }
119078365411SKent Overstreet 
1191cafe5635SKent Overstreet /* Garbage collection */
1192cafe5635SKent Overstreet 
1193487dded8SKent Overstreet static uint8_t __bch_btree_mark_key(struct cache_set *c, int level,
1194487dded8SKent Overstreet 				    struct bkey *k)
1195cafe5635SKent Overstreet {
1196cafe5635SKent Overstreet 	uint8_t stale = 0;
11976f10f7d1SColy Li 	unsigned int i;
1198cafe5635SKent Overstreet 	struct bucket *g;
1199cafe5635SKent Overstreet 
1200cafe5635SKent Overstreet 	/*
1201cafe5635SKent Overstreet 	 * ptr_invalid() can't return true for the keys that mark btree nodes as
1202cafe5635SKent Overstreet 	 * freed, but since ptr_bad() returns true we'll never actually use them
1203cafe5635SKent Overstreet 	 * for anything and thus we don't want mark their pointers here
1204cafe5635SKent Overstreet 	 */
1205cafe5635SKent Overstreet 	if (!bkey_cmp(k, &ZERO_KEY))
1206cafe5635SKent Overstreet 		return stale;
1207cafe5635SKent Overstreet 
1208cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++) {
1209cafe5635SKent Overstreet 		if (!ptr_available(c, k, i))
1210cafe5635SKent Overstreet 			continue;
1211cafe5635SKent Overstreet 
1212cafe5635SKent Overstreet 		g = PTR_BUCKET(c, k, i);
1213cafe5635SKent Overstreet 
12143a2fd9d5SKent Overstreet 		if (gen_after(g->last_gc, PTR_GEN(k, i)))
12153a2fd9d5SKent Overstreet 			g->last_gc = PTR_GEN(k, i);
1216cafe5635SKent Overstreet 
1217cafe5635SKent Overstreet 		if (ptr_stale(c, k, i)) {
1218cafe5635SKent Overstreet 			stale = max(stale, ptr_stale(c, k, i));
1219cafe5635SKent Overstreet 			continue;
1220cafe5635SKent Overstreet 		}
1221cafe5635SKent Overstreet 
1222cafe5635SKent Overstreet 		cache_bug_on(GC_MARK(g) &&
1223cafe5635SKent Overstreet 			     (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1224cafe5635SKent Overstreet 			     c, "inconsistent ptrs: mark = %llu, level = %i",
1225cafe5635SKent Overstreet 			     GC_MARK(g), level);
1226cafe5635SKent Overstreet 
1227cafe5635SKent Overstreet 		if (level)
1228cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_METADATA);
1229cafe5635SKent Overstreet 		else if (KEY_DIRTY(k))
1230cafe5635SKent Overstreet 			SET_GC_MARK(g, GC_MARK_DIRTY);
12314fe6a816SKent Overstreet 		else if (!GC_MARK(g))
12324fe6a816SKent Overstreet 			SET_GC_MARK(g, GC_MARK_RECLAIMABLE);
1233cafe5635SKent Overstreet 
1234cafe5635SKent Overstreet 		/* guard against overflow */
12356f10f7d1SColy Li 		SET_GC_SECTORS_USED(g, min_t(unsigned int,
1236cafe5635SKent Overstreet 					     GC_SECTORS_USED(g) + KEY_SIZE(k),
123794717447SDarrick J. Wong 					     MAX_GC_SECTORS_USED));
1238cafe5635SKent Overstreet 
1239cafe5635SKent Overstreet 		BUG_ON(!GC_SECTORS_USED(g));
1240cafe5635SKent Overstreet 	}
1241cafe5635SKent Overstreet 
1242cafe5635SKent Overstreet 	return stale;
1243cafe5635SKent Overstreet }
1244cafe5635SKent Overstreet 
1245cafe5635SKent Overstreet #define btree_mark_key(b, k)	__bch_btree_mark_key(b->c, b->level, k)
1246cafe5635SKent Overstreet 
1247487dded8SKent Overstreet void bch_initial_mark_key(struct cache_set *c, int level, struct bkey *k)
1248487dded8SKent Overstreet {
12496f10f7d1SColy Li 	unsigned int i;
1250487dded8SKent Overstreet 
1251487dded8SKent Overstreet 	for (i = 0; i < KEY_PTRS(k); i++)
1252487dded8SKent Overstreet 		if (ptr_available(c, k, i) &&
1253487dded8SKent Overstreet 		    !ptr_stale(c, k, i)) {
1254487dded8SKent Overstreet 			struct bucket *b = PTR_BUCKET(c, k, i);
1255487dded8SKent Overstreet 
1256487dded8SKent Overstreet 			b->gen = PTR_GEN(k, i);
1257487dded8SKent Overstreet 
1258487dded8SKent Overstreet 			if (level && bkey_cmp(k, &ZERO_KEY))
1259487dded8SKent Overstreet 				b->prio = BTREE_PRIO;
1260487dded8SKent Overstreet 			else if (!level && b->prio == BTREE_PRIO)
1261487dded8SKent Overstreet 				b->prio = INITIAL_PRIO;
1262487dded8SKent Overstreet 		}
1263487dded8SKent Overstreet 
1264487dded8SKent Overstreet 	__bch_btree_mark_key(c, level, k);
1265487dded8SKent Overstreet }
1266487dded8SKent Overstreet 
1267d44c2f9eSTang Junhui void bch_update_bucket_in_use(struct cache_set *c, struct gc_stat *stats)
1268d44c2f9eSTang Junhui {
1269d44c2f9eSTang Junhui 	stats->in_use = (c->nbuckets - c->avail_nbuckets) * 100 / c->nbuckets;
1270d44c2f9eSTang Junhui }
1271d44c2f9eSTang Junhui 
1272a1f0358bSKent Overstreet static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1273cafe5635SKent Overstreet {
1274cafe5635SKent Overstreet 	uint8_t stale = 0;
12756f10f7d1SColy Li 	unsigned int keys = 0, good_keys = 0;
1276cafe5635SKent Overstreet 	struct bkey *k;
1277cafe5635SKent Overstreet 	struct btree_iter iter;
1278cafe5635SKent Overstreet 	struct bset_tree *t;
1279cafe5635SKent Overstreet 
1280cafe5635SKent Overstreet 	gc->nodes++;
1281cafe5635SKent Overstreet 
1282c052dd9aSKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid) {
1283cafe5635SKent Overstreet 		stale = max(stale, btree_mark_key(b, k));
1284a1f0358bSKent Overstreet 		keys++;
1285cafe5635SKent Overstreet 
1286a85e968eSKent Overstreet 		if (bch_ptr_bad(&b->keys, k))
1287cafe5635SKent Overstreet 			continue;
1288cafe5635SKent Overstreet 
1289cafe5635SKent Overstreet 		gc->key_bytes += bkey_u64s(k);
1290cafe5635SKent Overstreet 		gc->nkeys++;
1291a1f0358bSKent Overstreet 		good_keys++;
1292cafe5635SKent Overstreet 
1293cafe5635SKent Overstreet 		gc->data += KEY_SIZE(k);
1294cafe5635SKent Overstreet 	}
1295cafe5635SKent Overstreet 
1296a85e968eSKent Overstreet 	for (t = b->keys.set; t <= &b->keys.set[b->keys.nsets]; t++)
1297cafe5635SKent Overstreet 		btree_bug_on(t->size &&
1298a85e968eSKent Overstreet 			     bset_written(&b->keys, t) &&
1299cafe5635SKent Overstreet 			     bkey_cmp(&b->key, &t->end) < 0,
1300cafe5635SKent Overstreet 			     b, "found short btree key in gc");
1301cafe5635SKent Overstreet 
1302a1f0358bSKent Overstreet 	if (b->c->gc_always_rewrite)
1303a1f0358bSKent Overstreet 		return true;
1304a1f0358bSKent Overstreet 
1305a1f0358bSKent Overstreet 	if (stale > 10)
1306a1f0358bSKent Overstreet 		return true;
1307a1f0358bSKent Overstreet 
1308a1f0358bSKent Overstreet 	if ((keys - good_keys) * 2 > keys)
1309a1f0358bSKent Overstreet 		return true;
1310a1f0358bSKent Overstreet 
1311a1f0358bSKent Overstreet 	return false;
1312cafe5635SKent Overstreet }
1313cafe5635SKent Overstreet 
1314a1f0358bSKent Overstreet #define GC_MERGE_NODES	4U
1315cafe5635SKent Overstreet 
1316cafe5635SKent Overstreet struct gc_merge_info {
1317cafe5635SKent Overstreet 	struct btree	*b;
13186f10f7d1SColy Li 	unsigned int	keys;
1319cafe5635SKent Overstreet };
1320cafe5635SKent Overstreet 
1321fc2d5988SColy Li static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
1322fc2d5988SColy Li 				 struct keylist *insert_keys,
1323fc2d5988SColy Li 				 atomic_t *journal_ref,
1324fc2d5988SColy Li 				 struct bkey *replace_key);
1325a1f0358bSKent Overstreet 
1326a1f0358bSKent Overstreet static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
13270a63b66dSKent Overstreet 			     struct gc_stat *gc, struct gc_merge_info *r)
1328cafe5635SKent Overstreet {
13296f10f7d1SColy Li 	unsigned int i, nodes = 0, keys = 0, blocks;
1330a1f0358bSKent Overstreet 	struct btree *new_nodes[GC_MERGE_NODES];
13310a63b66dSKent Overstreet 	struct keylist keylist;
1332b54d6934SKent Overstreet 	struct closure cl;
1333a1f0358bSKent Overstreet 	struct bkey *k;
1334b54d6934SKent Overstreet 
13350a63b66dSKent Overstreet 	bch_keylist_init(&keylist);
13360a63b66dSKent Overstreet 
13370a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL))
13380a63b66dSKent Overstreet 		return 0;
13390a63b66dSKent Overstreet 
1340a1f0358bSKent Overstreet 	memset(new_nodes, 0, sizeof(new_nodes));
1341b54d6934SKent Overstreet 	closure_init_stack(&cl);
1342cafe5635SKent Overstreet 
1343a1f0358bSKent Overstreet 	while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1344cafe5635SKent Overstreet 		keys += r[nodes++].keys;
1345cafe5635SKent Overstreet 
1346cafe5635SKent Overstreet 	blocks = btree_default_blocks(b->c) * 2 / 3;
1347cafe5635SKent Overstreet 
1348cafe5635SKent Overstreet 	if (nodes < 2 ||
1349a85e968eSKent Overstreet 	    __set_blocks(b->keys.set[0].data, keys,
13504e1ebae3SColy Li 			 block_bytes(b->c->cache)) > blocks * (nodes - 1))
1351a1f0358bSKent Overstreet 		return 0;
1352cafe5635SKent Overstreet 
1353a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
13540a63b66dSKent Overstreet 		new_nodes[i] = btree_node_alloc_replacement(r[i].b, NULL);
1355a1f0358bSKent Overstreet 		if (IS_ERR_OR_NULL(new_nodes[i]))
1356a1f0358bSKent Overstreet 			goto out_nocoalesce;
1357cafe5635SKent Overstreet 	}
1358cafe5635SKent Overstreet 
13590a63b66dSKent Overstreet 	/*
13600a63b66dSKent Overstreet 	 * We have to check the reserve here, after we've allocated our new
13610a63b66dSKent Overstreet 	 * nodes, to make sure the insert below will succeed - we also check
13620a63b66dSKent Overstreet 	 * before as an optimization to potentially avoid a bunch of expensive
13630a63b66dSKent Overstreet 	 * allocs/sorts
13640a63b66dSKent Overstreet 	 */
13650a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL))
13660a63b66dSKent Overstreet 		goto out_nocoalesce;
13670a63b66dSKent Overstreet 
13682a285686SKent Overstreet 	for (i = 0; i < nodes; i++)
13692a285686SKent Overstreet 		mutex_lock(&new_nodes[i]->write_lock);
13702a285686SKent Overstreet 
1371cafe5635SKent Overstreet 	for (i = nodes - 1; i > 0; --i) {
1372ee811287SKent Overstreet 		struct bset *n1 = btree_bset_first(new_nodes[i]);
1373ee811287SKent Overstreet 		struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
1374cafe5635SKent Overstreet 		struct bkey *k, *last = NULL;
1375cafe5635SKent Overstreet 
1376cafe5635SKent Overstreet 		keys = 0;
1377cafe5635SKent Overstreet 
1378a1f0358bSKent Overstreet 		if (i > 1) {
1379cafe5635SKent Overstreet 			for (k = n2->start;
1380fafff81cSKent Overstreet 			     k < bset_bkey_last(n2);
1381cafe5635SKent Overstreet 			     k = bkey_next(k)) {
1382cafe5635SKent Overstreet 				if (__set_blocks(n1, n1->keys + keys +
1383ee811287SKent Overstreet 						 bkey_u64s(k),
13844e1ebae3SColy Li 						 block_bytes(b->c->cache)) > blocks)
1385cafe5635SKent Overstreet 					break;
1386cafe5635SKent Overstreet 
1387cafe5635SKent Overstreet 				last = k;
1388cafe5635SKent Overstreet 				keys += bkey_u64s(k);
1389cafe5635SKent Overstreet 			}
1390a1f0358bSKent Overstreet 		} else {
1391a1f0358bSKent Overstreet 			/*
1392a1f0358bSKent Overstreet 			 * Last node we're not getting rid of - we're getting
1393a1f0358bSKent Overstreet 			 * rid of the node at r[0]. Have to try and fit all of
1394a1f0358bSKent Overstreet 			 * the remaining keys into this node; we can't ensure
1395a1f0358bSKent Overstreet 			 * they will always fit due to rounding and variable
1396a1f0358bSKent Overstreet 			 * length keys (shouldn't be possible in practice,
1397a1f0358bSKent Overstreet 			 * though)
1398a1f0358bSKent Overstreet 			 */
1399a1f0358bSKent Overstreet 			if (__set_blocks(n1, n1->keys + n2->keys,
14004e1ebae3SColy Li 					 block_bytes(b->c->cache)) >
1401ee811287SKent Overstreet 			    btree_blocks(new_nodes[i]))
1402be23e837SZhiqiang Liu 				goto out_unlock_nocoalesce;
1403a1f0358bSKent Overstreet 
1404a1f0358bSKent Overstreet 			keys = n2->keys;
1405a1f0358bSKent Overstreet 			/* Take the key of the node we're getting rid of */
1406a1f0358bSKent Overstreet 			last = &r->b->key;
1407a1f0358bSKent Overstreet 		}
1408cafe5635SKent Overstreet 
14094e1ebae3SColy Li 		BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c->cache)) >
1410ee811287SKent Overstreet 		       btree_blocks(new_nodes[i]));
1411cafe5635SKent Overstreet 
1412a1f0358bSKent Overstreet 		if (last)
1413a1f0358bSKent Overstreet 			bkey_copy_key(&new_nodes[i]->key, last);
1414cafe5635SKent Overstreet 
1415fafff81cSKent Overstreet 		memcpy(bset_bkey_last(n1),
1416cafe5635SKent Overstreet 		       n2->start,
1417fafff81cSKent Overstreet 		       (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
1418cafe5635SKent Overstreet 
1419cafe5635SKent Overstreet 		n1->keys += keys;
1420a1f0358bSKent Overstreet 		r[i].keys = n1->keys;
1421cafe5635SKent Overstreet 
1422cafe5635SKent Overstreet 		memmove(n2->start,
1423fafff81cSKent Overstreet 			bset_bkey_idx(n2, keys),
1424fafff81cSKent Overstreet 			(void *) bset_bkey_last(n2) -
1425fafff81cSKent Overstreet 			(void *) bset_bkey_idx(n2, keys));
1426cafe5635SKent Overstreet 
1427cafe5635SKent Overstreet 		n2->keys -= keys;
1428cafe5635SKent Overstreet 
14290a63b66dSKent Overstreet 		if (__bch_keylist_realloc(&keylist,
1430085d2a3dSKent Overstreet 					  bkey_u64s(&new_nodes[i]->key)))
1431be23e837SZhiqiang Liu 			goto out_unlock_nocoalesce;
1432a1f0358bSKent Overstreet 
1433a1f0358bSKent Overstreet 		bch_btree_node_write(new_nodes[i], &cl);
14340a63b66dSKent Overstreet 		bch_keylist_add(&keylist, &new_nodes[i]->key);
1435cafe5635SKent Overstreet 	}
1436cafe5635SKent Overstreet 
14372a285686SKent Overstreet 	for (i = 0; i < nodes; i++)
14382a285686SKent Overstreet 		mutex_unlock(&new_nodes[i]->write_lock);
14392a285686SKent Overstreet 
144005335cffSKent Overstreet 	closure_sync(&cl);
144105335cffSKent Overstreet 
144205335cffSKent Overstreet 	/* We emptied out this node */
144305335cffSKent Overstreet 	BUG_ON(btree_bset_first(new_nodes[0])->keys);
144405335cffSKent Overstreet 	btree_node_free(new_nodes[0]);
144505335cffSKent Overstreet 	rw_unlock(true, new_nodes[0]);
1446400ffaa2SSlava Pestov 	new_nodes[0] = NULL;
144705335cffSKent Overstreet 
1448a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
14490a63b66dSKent Overstreet 		if (__bch_keylist_realloc(&keylist, bkey_u64s(&r[i].b->key)))
1450a1f0358bSKent Overstreet 			goto out_nocoalesce;
1451a1f0358bSKent Overstreet 
14520a63b66dSKent Overstreet 		make_btree_freeing_key(r[i].b, keylist.top);
14530a63b66dSKent Overstreet 		bch_keylist_push(&keylist);
1454a1f0358bSKent Overstreet 	}
1455a1f0358bSKent Overstreet 
14560a63b66dSKent Overstreet 	bch_btree_insert_node(b, op, &keylist, NULL, NULL);
14570a63b66dSKent Overstreet 	BUG_ON(!bch_keylist_empty(&keylist));
1458a1f0358bSKent Overstreet 
1459a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++) {
1460a1f0358bSKent Overstreet 		btree_node_free(r[i].b);
1461a1f0358bSKent Overstreet 		rw_unlock(true, r[i].b);
1462a1f0358bSKent Overstreet 
1463a1f0358bSKent Overstreet 		r[i].b = new_nodes[i];
1464a1f0358bSKent Overstreet 	}
1465a1f0358bSKent Overstreet 
1466a1f0358bSKent Overstreet 	memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1467a1f0358bSKent Overstreet 	r[nodes - 1].b = ERR_PTR(-EINTR);
1468cafe5635SKent Overstreet 
1469c37511b8SKent Overstreet 	trace_bcache_btree_gc_coalesce(nodes);
1470cafe5635SKent Overstreet 	gc->nodes--;
1471cafe5635SKent Overstreet 
14720a63b66dSKent Overstreet 	bch_keylist_free(&keylist);
14730a63b66dSKent Overstreet 
1474a1f0358bSKent Overstreet 	/* Invalidated our iterator */
1475a1f0358bSKent Overstreet 	return -EINTR;
1476a1f0358bSKent Overstreet 
1477be23e837SZhiqiang Liu out_unlock_nocoalesce:
1478be23e837SZhiqiang Liu 	for (i = 0; i < nodes; i++)
1479be23e837SZhiqiang Liu 		mutex_unlock(&new_nodes[i]->write_lock);
1480be23e837SZhiqiang Liu 
1481a1f0358bSKent Overstreet out_nocoalesce:
1482a1f0358bSKent Overstreet 	closure_sync(&cl);
1483a1f0358bSKent Overstreet 
14840a63b66dSKent Overstreet 	while ((k = bch_keylist_pop(&keylist)))
1485a1f0358bSKent Overstreet 		if (!bkey_cmp(k, &ZERO_KEY))
1486a1f0358bSKent Overstreet 			atomic_dec(&b->c->prio_blocked);
1487f16277caSShenghui Wang 	bch_keylist_free(&keylist);
1488a1f0358bSKent Overstreet 
1489a1f0358bSKent Overstreet 	for (i = 0; i < nodes; i++)
1490a1f0358bSKent Overstreet 		if (!IS_ERR_OR_NULL(new_nodes[i])) {
1491a1f0358bSKent Overstreet 			btree_node_free(new_nodes[i]);
1492a1f0358bSKent Overstreet 			rw_unlock(true, new_nodes[i]);
1493a1f0358bSKent Overstreet 		}
1494a1f0358bSKent Overstreet 	return 0;
1495a1f0358bSKent Overstreet }
1496a1f0358bSKent Overstreet 
14970a63b66dSKent Overstreet static int btree_gc_rewrite_node(struct btree *b, struct btree_op *op,
14980a63b66dSKent Overstreet 				 struct btree *replace)
14990a63b66dSKent Overstreet {
15000a63b66dSKent Overstreet 	struct keylist keys;
15010a63b66dSKent Overstreet 	struct btree *n;
15020a63b66dSKent Overstreet 
15030a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL))
15040a63b66dSKent Overstreet 		return 0;
15050a63b66dSKent Overstreet 
15060a63b66dSKent Overstreet 	n = btree_node_alloc_replacement(replace, NULL);
15070a63b66dSKent Overstreet 
15080a63b66dSKent Overstreet 	/* recheck reserve after allocating replacement node */
15090a63b66dSKent Overstreet 	if (btree_check_reserve(b, NULL)) {
15100a63b66dSKent Overstreet 		btree_node_free(n);
15110a63b66dSKent Overstreet 		rw_unlock(true, n);
15120a63b66dSKent Overstreet 		return 0;
15130a63b66dSKent Overstreet 	}
15140a63b66dSKent Overstreet 
15150a63b66dSKent Overstreet 	bch_btree_node_write_sync(n);
15160a63b66dSKent Overstreet 
15170a63b66dSKent Overstreet 	bch_keylist_init(&keys);
15180a63b66dSKent Overstreet 	bch_keylist_add(&keys, &n->key);
15190a63b66dSKent Overstreet 
15200a63b66dSKent Overstreet 	make_btree_freeing_key(replace, keys.top);
15210a63b66dSKent Overstreet 	bch_keylist_push(&keys);
15220a63b66dSKent Overstreet 
15230a63b66dSKent Overstreet 	bch_btree_insert_node(b, op, &keys, NULL, NULL);
15240a63b66dSKent Overstreet 	BUG_ON(!bch_keylist_empty(&keys));
15250a63b66dSKent Overstreet 
15260a63b66dSKent Overstreet 	btree_node_free(replace);
15270a63b66dSKent Overstreet 	rw_unlock(true, n);
15280a63b66dSKent Overstreet 
15290a63b66dSKent Overstreet 	/* Invalidated our iterator */
15300a63b66dSKent Overstreet 	return -EINTR;
15310a63b66dSKent Overstreet }
15320a63b66dSKent Overstreet 
15336f10f7d1SColy Li static unsigned int btree_gc_count_keys(struct btree *b)
1534a1f0358bSKent Overstreet {
1535a1f0358bSKent Overstreet 	struct bkey *k;
1536a1f0358bSKent Overstreet 	struct btree_iter iter;
15376f10f7d1SColy Li 	unsigned int ret = 0;
1538a1f0358bSKent Overstreet 
1539c052dd9aSKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_bad)
1540a1f0358bSKent Overstreet 		ret += bkey_u64s(k);
1541a1f0358bSKent Overstreet 
1542a1f0358bSKent Overstreet 	return ret;
1543cafe5635SKent Overstreet }
1544cafe5635SKent Overstreet 
15457f4a59deSTang Junhui static size_t btree_gc_min_nodes(struct cache_set *c)
15467f4a59deSTang Junhui {
15477f4a59deSTang Junhui 	size_t min_nodes;
15487f4a59deSTang Junhui 
15497f4a59deSTang Junhui 	/*
15507f4a59deSTang Junhui 	 * Since incremental GC would stop 100ms when front
15517f4a59deSTang Junhui 	 * side I/O comes, so when there are many btree nodes,
15527f4a59deSTang Junhui 	 * if GC only processes constant (100) nodes each time,
15537f4a59deSTang Junhui 	 * GC would last a long time, and the front side I/Os
15547f4a59deSTang Junhui 	 * would run out of the buckets (since no new bucket
15557f4a59deSTang Junhui 	 * can be allocated during GC), and be blocked again.
15567f4a59deSTang Junhui 	 * So GC should not process constant nodes, but varied
15577f4a59deSTang Junhui 	 * nodes according to the number of btree nodes, which
15587f4a59deSTang Junhui 	 * realized by dividing GC into constant(100) times,
15597f4a59deSTang Junhui 	 * so when there are many btree nodes, GC can process
15607f4a59deSTang Junhui 	 * more nodes each time, otherwise, GC will process less
15617f4a59deSTang Junhui 	 * nodes each time (but no less than MIN_GC_NODES)
15627f4a59deSTang Junhui 	 */
15637f4a59deSTang Junhui 	min_nodes = c->gc_stats.nodes / MAX_GC_TIMES;
15647f4a59deSTang Junhui 	if (min_nodes < MIN_GC_NODES)
15657f4a59deSTang Junhui 		min_nodes = MIN_GC_NODES;
15667f4a59deSTang Junhui 
15677f4a59deSTang Junhui 	return min_nodes;
15687f4a59deSTang Junhui }
15697f4a59deSTang Junhui 
15707f4a59deSTang Junhui 
1571cafe5635SKent Overstreet static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1572cafe5635SKent Overstreet 			    struct closure *writes, struct gc_stat *gc)
1573cafe5635SKent Overstreet {
1574a1f0358bSKent Overstreet 	int ret = 0;
1575a1f0358bSKent Overstreet 	bool should_rewrite;
1576a1f0358bSKent Overstreet 	struct bkey *k;
1577a1f0358bSKent Overstreet 	struct btree_iter iter;
1578cafe5635SKent Overstreet 	struct gc_merge_info r[GC_MERGE_NODES];
15792a285686SKent Overstreet 	struct gc_merge_info *i, *last = r + ARRAY_SIZE(r) - 1;
1580cafe5635SKent Overstreet 
1581c052dd9aSKent Overstreet 	bch_btree_iter_init(&b->keys, &iter, &b->c->gc_done);
1582cafe5635SKent Overstreet 
15832a285686SKent Overstreet 	for (i = r; i < r + ARRAY_SIZE(r); i++)
15842a285686SKent Overstreet 		i->b = ERR_PTR(-EINTR);
1585cafe5635SKent Overstreet 
1586a1f0358bSKent Overstreet 	while (1) {
1587a85e968eSKent Overstreet 		k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad);
1588a1f0358bSKent Overstreet 		if (k) {
15890a63b66dSKent Overstreet 			r->b = bch_btree_node_get(b->c, op, k, b->level - 1,
15902452cc89SSlava Pestov 						  true, b);
1591cafe5635SKent Overstreet 			if (IS_ERR(r->b)) {
1592cafe5635SKent Overstreet 				ret = PTR_ERR(r->b);
1593cafe5635SKent Overstreet 				break;
1594cafe5635SKent Overstreet 			}
1595cafe5635SKent Overstreet 
1596a1f0358bSKent Overstreet 			r->keys = btree_gc_count_keys(r->b);
1597cafe5635SKent Overstreet 
15980a63b66dSKent Overstreet 			ret = btree_gc_coalesce(b, op, gc, r);
1599a1f0358bSKent Overstreet 			if (ret)
1600cafe5635SKent Overstreet 				break;
1601cafe5635SKent Overstreet 		}
1602cafe5635SKent Overstreet 
1603a1f0358bSKent Overstreet 		if (!last->b)
1604a1f0358bSKent Overstreet 			break;
1605cafe5635SKent Overstreet 
1606a1f0358bSKent Overstreet 		if (!IS_ERR(last->b)) {
1607a1f0358bSKent Overstreet 			should_rewrite = btree_gc_mark_node(last->b, gc);
16080a63b66dSKent Overstreet 			if (should_rewrite) {
16090a63b66dSKent Overstreet 				ret = btree_gc_rewrite_node(b, op, last->b);
16100a63b66dSKent Overstreet 				if (ret)
1611a1f0358bSKent Overstreet 					break;
1612a1f0358bSKent Overstreet 			}
1613a1f0358bSKent Overstreet 
1614a1f0358bSKent Overstreet 			if (last->b->level) {
1615a1f0358bSKent Overstreet 				ret = btree_gc_recurse(last->b, op, writes, gc);
1616a1f0358bSKent Overstreet 				if (ret)
1617a1f0358bSKent Overstreet 					break;
1618a1f0358bSKent Overstreet 			}
1619a1f0358bSKent Overstreet 
1620a1f0358bSKent Overstreet 			bkey_copy_key(&b->c->gc_done, &last->b->key);
1621a1f0358bSKent Overstreet 
1622a1f0358bSKent Overstreet 			/*
1623a1f0358bSKent Overstreet 			 * Must flush leaf nodes before gc ends, since replace
1624a1f0358bSKent Overstreet 			 * operations aren't journalled
1625cafe5635SKent Overstreet 			 */
16262a285686SKent Overstreet 			mutex_lock(&last->b->write_lock);
1627a1f0358bSKent Overstreet 			if (btree_node_dirty(last->b))
1628a1f0358bSKent Overstreet 				bch_btree_node_write(last->b, writes);
16292a285686SKent Overstreet 			mutex_unlock(&last->b->write_lock);
1630a1f0358bSKent Overstreet 			rw_unlock(true, last->b);
1631a1f0358bSKent Overstreet 		}
1632a1f0358bSKent Overstreet 
1633a1f0358bSKent Overstreet 		memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1634a1f0358bSKent Overstreet 		r->b = NULL;
1635a1f0358bSKent Overstreet 
16365c25c4fcSTang Junhui 		if (atomic_read(&b->c->search_inflight) &&
16377f4a59deSTang Junhui 		    gc->nodes >= gc->nodes_pre + btree_gc_min_nodes(b->c)) {
16385c25c4fcSTang Junhui 			gc->nodes_pre =  gc->nodes;
16395c25c4fcSTang Junhui 			ret = -EAGAIN;
16405c25c4fcSTang Junhui 			break;
16415c25c4fcSTang Junhui 		}
16425c25c4fcSTang Junhui 
1643cafe5635SKent Overstreet 		if (need_resched()) {
1644cafe5635SKent Overstreet 			ret = -EAGAIN;
1645cafe5635SKent Overstreet 			break;
1646cafe5635SKent Overstreet 		}
1647cafe5635SKent Overstreet 	}
1648cafe5635SKent Overstreet 
16492a285686SKent Overstreet 	for (i = r; i < r + ARRAY_SIZE(r); i++)
16502a285686SKent Overstreet 		if (!IS_ERR_OR_NULL(i->b)) {
16512a285686SKent Overstreet 			mutex_lock(&i->b->write_lock);
16522a285686SKent Overstreet 			if (btree_node_dirty(i->b))
16532a285686SKent Overstreet 				bch_btree_node_write(i->b, writes);
16542a285686SKent Overstreet 			mutex_unlock(&i->b->write_lock);
16552a285686SKent Overstreet 			rw_unlock(true, i->b);
1656a1f0358bSKent Overstreet 		}
1657cafe5635SKent Overstreet 
1658cafe5635SKent Overstreet 	return ret;
1659cafe5635SKent Overstreet }
1660cafe5635SKent Overstreet 
1661cafe5635SKent Overstreet static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1662cafe5635SKent Overstreet 			     struct closure *writes, struct gc_stat *gc)
1663cafe5635SKent Overstreet {
1664cafe5635SKent Overstreet 	struct btree *n = NULL;
1665a1f0358bSKent Overstreet 	int ret = 0;
1666a1f0358bSKent Overstreet 	bool should_rewrite;
1667cafe5635SKent Overstreet 
1668a1f0358bSKent Overstreet 	should_rewrite = btree_gc_mark_node(b, gc);
1669a1f0358bSKent Overstreet 	if (should_rewrite) {
16700a63b66dSKent Overstreet 		n = btree_node_alloc_replacement(b, NULL);
1671cafe5635SKent Overstreet 
1672cafe5635SKent Overstreet 		if (!IS_ERR_OR_NULL(n)) {
1673a1f0358bSKent Overstreet 			bch_btree_node_write_sync(n);
16742a285686SKent Overstreet 
1675a1f0358bSKent Overstreet 			bch_btree_set_root(n);
1676a1f0358bSKent Overstreet 			btree_node_free(b);
1677a1f0358bSKent Overstreet 			rw_unlock(true, n);
1678a1f0358bSKent Overstreet 
1679a1f0358bSKent Overstreet 			return -EINTR;
1680cafe5635SKent Overstreet 		}
1681a1f0358bSKent Overstreet 	}
1682a1f0358bSKent Overstreet 
1683487dded8SKent Overstreet 	__bch_btree_mark_key(b->c, b->level + 1, &b->key);
1684487dded8SKent Overstreet 
1685a1f0358bSKent Overstreet 	if (b->level) {
1686a1f0358bSKent Overstreet 		ret = btree_gc_recurse(b, op, writes, gc);
1687a1f0358bSKent Overstreet 		if (ret)
1688a1f0358bSKent Overstreet 			return ret;
1689a1f0358bSKent Overstreet 	}
1690a1f0358bSKent Overstreet 
1691a1f0358bSKent Overstreet 	bkey_copy_key(&b->c->gc_done, &b->key);
1692cafe5635SKent Overstreet 
1693cafe5635SKent Overstreet 	return ret;
1694cafe5635SKent Overstreet }
1695cafe5635SKent Overstreet 
1696cafe5635SKent Overstreet static void btree_gc_start(struct cache_set *c)
1697cafe5635SKent Overstreet {
1698cafe5635SKent Overstreet 	struct cache *ca;
1699cafe5635SKent Overstreet 	struct bucket *b;
1700cafe5635SKent Overstreet 
1701cafe5635SKent Overstreet 	if (!c->gc_mark_valid)
1702cafe5635SKent Overstreet 		return;
1703cafe5635SKent Overstreet 
1704cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1705cafe5635SKent Overstreet 
1706cafe5635SKent Overstreet 	c->gc_mark_valid = 0;
1707cafe5635SKent Overstreet 	c->gc_done = ZERO_KEY;
1708cafe5635SKent Overstreet 
170908fdb2cdSColy Li 	ca = c->cache;
1710cafe5635SKent Overstreet 	for_each_bucket(b, ca) {
17113a2fd9d5SKent Overstreet 		b->last_gc = b->gen;
171229ebf465SKent Overstreet 		if (!atomic_read(&b->pin)) {
17134fe6a816SKent Overstreet 			SET_GC_MARK(b, 0);
171429ebf465SKent Overstreet 			SET_GC_SECTORS_USED(b, 0);
171529ebf465SKent Overstreet 		}
1716cafe5635SKent Overstreet 	}
1717cafe5635SKent Overstreet 
1718cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1719cafe5635SKent Overstreet }
1720cafe5635SKent Overstreet 
1721d44c2f9eSTang Junhui static void bch_btree_gc_finish(struct cache_set *c)
1722cafe5635SKent Overstreet {
1723cafe5635SKent Overstreet 	struct bucket *b;
1724cafe5635SKent Overstreet 	struct cache *ca;
172508fdb2cdSColy Li 	unsigned int i, j;
172608fdb2cdSColy Li 	uint64_t *k;
1727cafe5635SKent Overstreet 
1728cafe5635SKent Overstreet 	mutex_lock(&c->bucket_lock);
1729cafe5635SKent Overstreet 
1730cafe5635SKent Overstreet 	set_gc_sectors(c);
1731cafe5635SKent Overstreet 	c->gc_mark_valid = 1;
1732cafe5635SKent Overstreet 	c->need_gc	= 0;
1733cafe5635SKent Overstreet 
1734cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1735cafe5635SKent Overstreet 		SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1736cafe5635SKent Overstreet 			    GC_MARK_METADATA);
1737cafe5635SKent Overstreet 
1738bf0a628aSNicholas Swenson 	/* don't reclaim buckets to which writeback keys point */
1739bf0a628aSNicholas Swenson 	rcu_read_lock();
17402831231dSColy Li 	for (i = 0; i < c->devices_max_used; i++) {
1741bf0a628aSNicholas Swenson 		struct bcache_device *d = c->devices[i];
1742bf0a628aSNicholas Swenson 		struct cached_dev *dc;
1743bf0a628aSNicholas Swenson 		struct keybuf_key *w, *n;
1744bf0a628aSNicholas Swenson 
1745bf0a628aSNicholas Swenson 		if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1746bf0a628aSNicholas Swenson 			continue;
1747bf0a628aSNicholas Swenson 		dc = container_of(d, struct cached_dev, disk);
1748bf0a628aSNicholas Swenson 
1749bf0a628aSNicholas Swenson 		spin_lock(&dc->writeback_keys.lock);
1750bf0a628aSNicholas Swenson 		rbtree_postorder_for_each_entry_safe(w, n,
1751bf0a628aSNicholas Swenson 					&dc->writeback_keys.keys, node)
1752bf0a628aSNicholas Swenson 			for (j = 0; j < KEY_PTRS(&w->key); j++)
1753bf0a628aSNicholas Swenson 				SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1754bf0a628aSNicholas Swenson 					    GC_MARK_DIRTY);
1755bf0a628aSNicholas Swenson 		spin_unlock(&dc->writeback_keys.lock);
1756bf0a628aSNicholas Swenson 	}
1757bf0a628aSNicholas Swenson 	rcu_read_unlock();
1758bf0a628aSNicholas Swenson 
1759d44c2f9eSTang Junhui 	c->avail_nbuckets = 0;
1760cafe5635SKent Overstreet 
176108fdb2cdSColy Li 	ca = c->cache;
1762cafe5635SKent Overstreet 	ca->invalidate_needs_gc = 0;
1763cafe5635SKent Overstreet 
176408fdb2cdSColy Li 	for (k = ca->sb.d; k < ca->sb.d + ca->sb.keys; k++)
176508fdb2cdSColy Li 		SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
1766cafe5635SKent Overstreet 
176708fdb2cdSColy Li 	for (k = ca->prio_buckets;
176808fdb2cdSColy Li 	     k < ca->prio_buckets + prio_buckets(ca) * 2; k++)
176908fdb2cdSColy Li 		SET_GC_MARK(ca->buckets + *k, GC_MARK_METADATA);
1770cafe5635SKent Overstreet 
1771cafe5635SKent Overstreet 	for_each_bucket(b, ca) {
1772cafe5635SKent Overstreet 		c->need_gc	= max(c->need_gc, bucket_gc_gen(b));
1773cafe5635SKent Overstreet 
17744fe6a816SKent Overstreet 		if (atomic_read(&b->pin))
17754fe6a816SKent Overstreet 			continue;
17764fe6a816SKent Overstreet 
17774fe6a816SKent Overstreet 		BUG_ON(!GC_MARK(b) && GC_SECTORS_USED(b));
17784fe6a816SKent Overstreet 
17794fe6a816SKent Overstreet 		if (!GC_MARK(b) || GC_MARK(b) == GC_MARK_RECLAIMABLE)
1780d44c2f9eSTang Junhui 			c->avail_nbuckets++;
1781cafe5635SKent Overstreet 	}
1782cafe5635SKent Overstreet 
1783cafe5635SKent Overstreet 	mutex_unlock(&c->bucket_lock);
1784cafe5635SKent Overstreet }
1785cafe5635SKent Overstreet 
178672a44517SKent Overstreet static void bch_btree_gc(struct cache_set *c)
1787cafe5635SKent Overstreet {
1788cafe5635SKent Overstreet 	int ret;
1789cafe5635SKent Overstreet 	struct gc_stat stats;
1790cafe5635SKent Overstreet 	struct closure writes;
1791cafe5635SKent Overstreet 	struct btree_op op;
1792cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
179357943511SKent Overstreet 
1794c37511b8SKent Overstreet 	trace_bcache_gc_start(c);
1795cafe5635SKent Overstreet 
1796cafe5635SKent Overstreet 	memset(&stats, 0, sizeof(struct gc_stat));
1797cafe5635SKent Overstreet 	closure_init_stack(&writes);
1798b54d6934SKent Overstreet 	bch_btree_op_init(&op, SHRT_MAX);
1799cafe5635SKent Overstreet 
1800cafe5635SKent Overstreet 	btree_gc_start(c);
1801cafe5635SKent Overstreet 
1802771f393eSColy Li 	/* if CACHE_SET_IO_DISABLE set, gc thread should stop too */
1803a1f0358bSKent Overstreet 	do {
1804feac1a70SColy Li 		ret = bcache_btree_root(gc_root, c, &op, &writes, &stats);
1805cafe5635SKent Overstreet 		closure_sync(&writes);
1806c5f1e5adSKent Overstreet 		cond_resched();
1807cafe5635SKent Overstreet 
18085c25c4fcSTang Junhui 		if (ret == -EAGAIN)
18095c25c4fcSTang Junhui 			schedule_timeout_interruptible(msecs_to_jiffies
18105c25c4fcSTang Junhui 						       (GC_SLEEP_MS));
18115c25c4fcSTang Junhui 		else if (ret)
181246f5aa88SJoe Perches 			pr_warn("gc failed!\n");
1813771f393eSColy Li 	} while (ret && !test_bit(CACHE_SET_IO_DISABLE, &c->flags));
1814cafe5635SKent Overstreet 
1815d44c2f9eSTang Junhui 	bch_btree_gc_finish(c);
181657943511SKent Overstreet 	wake_up_allocators(c);
181757943511SKent Overstreet 
1818169ef1cfSKent Overstreet 	bch_time_stats_update(&c->btree_gc_time, start_time);
1819cafe5635SKent Overstreet 
1820cafe5635SKent Overstreet 	stats.key_bytes *= sizeof(uint64_t);
1821cafe5635SKent Overstreet 	stats.data	<<= 9;
1822d44c2f9eSTang Junhui 	bch_update_bucket_in_use(c, &stats);
1823cafe5635SKent Overstreet 	memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1824cafe5635SKent Overstreet 
1825c37511b8SKent Overstreet 	trace_bcache_gc_end(c);
1826cafe5635SKent Overstreet 
182772a44517SKent Overstreet 	bch_moving_gc(c);
1828cafe5635SKent Overstreet }
1829cafe5635SKent Overstreet 
1830be628be0SKent Overstreet static bool gc_should_run(struct cache_set *c)
1831cafe5635SKent Overstreet {
183208fdb2cdSColy Li 	struct cache *ca = c->cache;
183372a44517SKent Overstreet 
1834be628be0SKent Overstreet 	if (ca->invalidate_needs_gc)
1835be628be0SKent Overstreet 		return true;
183672a44517SKent Overstreet 
1837be628be0SKent Overstreet 	if (atomic_read(&c->sectors_to_gc) < 0)
1838be628be0SKent Overstreet 		return true;
1839be628be0SKent Overstreet 
1840be628be0SKent Overstreet 	return false;
1841be628be0SKent Overstreet }
1842be628be0SKent Overstreet 
1843be628be0SKent Overstreet static int bch_gc_thread(void *arg)
1844be628be0SKent Overstreet {
1845be628be0SKent Overstreet 	struct cache_set *c = arg;
1846be628be0SKent Overstreet 
1847be628be0SKent Overstreet 	while (1) {
1848be628be0SKent Overstreet 		wait_event_interruptible(c->gc_wait,
1849771f393eSColy Li 			   kthread_should_stop() ||
1850771f393eSColy Li 			   test_bit(CACHE_SET_IO_DISABLE, &c->flags) ||
1851771f393eSColy Li 			   gc_should_run(c));
1852be628be0SKent Overstreet 
1853771f393eSColy Li 		if (kthread_should_stop() ||
1854771f393eSColy Li 		    test_bit(CACHE_SET_IO_DISABLE, &c->flags))
185572a44517SKent Overstreet 			break;
185672a44517SKent Overstreet 
1857be628be0SKent Overstreet 		set_gc_sectors(c);
1858be628be0SKent Overstreet 		bch_btree_gc(c);
185972a44517SKent Overstreet 	}
186072a44517SKent Overstreet 
1861771f393eSColy Li 	wait_for_kthread_stop();
186272a44517SKent Overstreet 	return 0;
186372a44517SKent Overstreet }
186472a44517SKent Overstreet 
186572a44517SKent Overstreet int bch_gc_thread_start(struct cache_set *c)
186672a44517SKent Overstreet {
1867be628be0SKent Overstreet 	c->gc_thread = kthread_run(bch_gc_thread, c, "bcache_gc");
18689d134117SVasyl Gomonovych 	return PTR_ERR_OR_ZERO(c->gc_thread);
1869cafe5635SKent Overstreet }
1870cafe5635SKent Overstreet 
1871cafe5635SKent Overstreet /* Initial partial gc */
1872cafe5635SKent Overstreet 
1873487dded8SKent Overstreet static int bch_btree_check_recurse(struct btree *b, struct btree_op *op)
1874cafe5635SKent Overstreet {
187550310164SKent Overstreet 	int ret = 0;
187650310164SKent Overstreet 	struct bkey *k, *p = NULL;
1877cafe5635SKent Overstreet 	struct btree_iter iter;
1878cafe5635SKent Overstreet 
1879487dded8SKent Overstreet 	for_each_key_filter(&b->keys, k, &iter, bch_ptr_invalid)
1880487dded8SKent Overstreet 		bch_initial_mark_key(b->c, b->level, k);
1881cafe5635SKent Overstreet 
1882487dded8SKent Overstreet 	bch_initial_mark_key(b->c, b->level + 1, &b->key);
1883cafe5635SKent Overstreet 
1884cafe5635SKent Overstreet 	if (b->level) {
1885c052dd9aSKent Overstreet 		bch_btree_iter_init(&b->keys, &iter, NULL);
1886cafe5635SKent Overstreet 
188750310164SKent Overstreet 		do {
1888a85e968eSKent Overstreet 			k = bch_btree_iter_next_filter(&iter, &b->keys,
1889a85e968eSKent Overstreet 						       bch_ptr_bad);
18907f4a59deSTang Junhui 			if (k) {
18912452cc89SSlava Pestov 				btree_node_prefetch(b, k);
18927f4a59deSTang Junhui 				/*
18937f4a59deSTang Junhui 				 * initiallize c->gc_stats.nodes
18947f4a59deSTang Junhui 				 * for incremental GC
18957f4a59deSTang Junhui 				 */
18967f4a59deSTang Junhui 				b->c->gc_stats.nodes++;
18977f4a59deSTang Junhui 			}
189850310164SKent Overstreet 
1899cafe5635SKent Overstreet 			if (p)
1900feac1a70SColy Li 				ret = bcache_btree(check_recurse, p, b, op);
1901cafe5635SKent Overstreet 
190250310164SKent Overstreet 			p = k;
190350310164SKent Overstreet 		} while (p && !ret);
1904cafe5635SKent Overstreet 	}
1905cafe5635SKent Overstreet 
1906487dded8SKent Overstreet 	return ret;
1907cafe5635SKent Overstreet }
1908cafe5635SKent Overstreet 
19098e710227SColy Li 
19108e710227SColy Li static int bch_btree_check_thread(void *arg)
1911cafe5635SKent Overstreet {
19128e710227SColy Li 	int ret;
19138e710227SColy Li 	struct btree_check_info *info = arg;
19148e710227SColy Li 	struct btree_check_state *check_state = info->state;
19158e710227SColy Li 	struct cache_set *c = check_state->c;
19168e710227SColy Li 	struct btree_iter iter;
19178e710227SColy Li 	struct bkey *k, *p;
19188e710227SColy Li 	int cur_idx, prev_idx, skip_nr;
19198e710227SColy Li 
19208e710227SColy Li 	k = p = NULL;
19218e710227SColy Li 	cur_idx = prev_idx = 0;
19228e710227SColy Li 	ret = 0;
19238e710227SColy Li 
19248e710227SColy Li 	/* root node keys are checked before thread created */
19258e710227SColy Li 	bch_btree_iter_init(&c->root->keys, &iter, NULL);
19268e710227SColy Li 	k = bch_btree_iter_next_filter(&iter, &c->root->keys, bch_ptr_bad);
19278e710227SColy Li 	BUG_ON(!k);
19288e710227SColy Li 
19298e710227SColy Li 	p = k;
19308e710227SColy Li 	while (k) {
19318e710227SColy Li 		/*
19328e710227SColy Li 		 * Fetch a root node key index, skip the keys which
19338e710227SColy Li 		 * should be fetched by other threads, then check the
19348e710227SColy Li 		 * sub-tree indexed by the fetched key.
19358e710227SColy Li 		 */
19368e710227SColy Li 		spin_lock(&check_state->idx_lock);
19378e710227SColy Li 		cur_idx = check_state->key_idx;
19388e710227SColy Li 		check_state->key_idx++;
19398e710227SColy Li 		spin_unlock(&check_state->idx_lock);
19408e710227SColy Li 
19418e710227SColy Li 		skip_nr = cur_idx - prev_idx;
19428e710227SColy Li 
19438e710227SColy Li 		while (skip_nr) {
19448e710227SColy Li 			k = bch_btree_iter_next_filter(&iter,
19458e710227SColy Li 						       &c->root->keys,
19468e710227SColy Li 						       bch_ptr_bad);
19478e710227SColy Li 			if (k)
19488e710227SColy Li 				p = k;
19498e710227SColy Li 			else {
19508e710227SColy Li 				/*
19518e710227SColy Li 				 * No more keys to check in root node,
19528e710227SColy Li 				 * current checking threads are enough,
19538e710227SColy Li 				 * stop creating more.
19548e710227SColy Li 				 */
19558e710227SColy Li 				atomic_set(&check_state->enough, 1);
19568e710227SColy Li 				/* Update check_state->enough earlier */
1957eb9b6666SColy Li 				smp_mb__after_atomic();
19588e710227SColy Li 				goto out;
19598e710227SColy Li 			}
19608e710227SColy Li 			skip_nr--;
19618e710227SColy Li 			cond_resched();
19628e710227SColy Li 		}
19638e710227SColy Li 
19648e710227SColy Li 		if (p) {
1965c18536a7SKent Overstreet 			struct btree_op op;
1966cafe5635SKent Overstreet 
19678e710227SColy Li 			btree_node_prefetch(c->root, p);
19688e710227SColy Li 			c->gc_stats.nodes++;
19698e710227SColy Li 			bch_btree_op_init(&op, 0);
19708e710227SColy Li 			ret = bcache_btree(check_recurse, p, c->root, &op);
19718e710227SColy Li 			if (ret)
19728e710227SColy Li 				goto out;
19738e710227SColy Li 		}
19748e710227SColy Li 		p = NULL;
19758e710227SColy Li 		prev_idx = cur_idx;
19768e710227SColy Li 		cond_resched();
19778e710227SColy Li 	}
1978cafe5635SKent Overstreet 
19798e710227SColy Li out:
19808e710227SColy Li 	info->result = ret;
19818e710227SColy Li 	/* update check_state->started among all CPUs */
1982eb9b6666SColy Li 	smp_mb__before_atomic();
19838e710227SColy Li 	if (atomic_dec_and_test(&check_state->started))
19848e710227SColy Li 		wake_up(&check_state->wait);
19858e710227SColy Li 
19868e710227SColy Li 	return ret;
19878e710227SColy Li }
19888e710227SColy Li 
19898e710227SColy Li 
19908e710227SColy Li 
19918e710227SColy Li static int bch_btree_chkthread_nr(void)
19928e710227SColy Li {
19938e710227SColy Li 	int n = num_online_cpus()/2;
19948e710227SColy Li 
19958e710227SColy Li 	if (n == 0)
19968e710227SColy Li 		n = 1;
19978e710227SColy Li 	else if (n > BCH_BTR_CHKTHREAD_MAX)
19988e710227SColy Li 		n = BCH_BTR_CHKTHREAD_MAX;
19998e710227SColy Li 
20008e710227SColy Li 	return n;
20018e710227SColy Li }
20028e710227SColy Li 
20038e710227SColy Li int bch_btree_check(struct cache_set *c)
20048e710227SColy Li {
20058e710227SColy Li 	int ret = 0;
20068e710227SColy Li 	int i;
20078e710227SColy Li 	struct bkey *k = NULL;
20088e710227SColy Li 	struct btree_iter iter;
20098e710227SColy Li 	struct btree_check_state *check_state;
20108e710227SColy Li 	char name[32];
20118e710227SColy Li 
20128e710227SColy Li 	/* check and mark root node keys */
20138e710227SColy Li 	for_each_key_filter(&c->root->keys, k, &iter, bch_ptr_invalid)
20148e710227SColy Li 		bch_initial_mark_key(c, c->root->level, k);
20158e710227SColy Li 
20168e710227SColy Li 	bch_initial_mark_key(c, c->root->level + 1, &c->root->key);
20178e710227SColy Li 
20188e710227SColy Li 	if (c->root->level == 0)
20198e710227SColy Li 		return 0;
20208e710227SColy Li 
20218e710227SColy Li 	check_state = kzalloc(sizeof(struct btree_check_state), GFP_KERNEL);
20228e710227SColy Li 	if (!check_state)
20238e710227SColy Li 		return -ENOMEM;
20248e710227SColy Li 
20258e710227SColy Li 	check_state->c = c;
20268e710227SColy Li 	check_state->total_threads = bch_btree_chkthread_nr();
20278e710227SColy Li 	check_state->key_idx = 0;
20288e710227SColy Li 	spin_lock_init(&check_state->idx_lock);
20298e710227SColy Li 	atomic_set(&check_state->started, 0);
20308e710227SColy Li 	atomic_set(&check_state->enough, 0);
20318e710227SColy Li 	init_waitqueue_head(&check_state->wait);
20328e710227SColy Li 
20338e710227SColy Li 	/*
20348e710227SColy Li 	 * Run multiple threads to check btree nodes in parallel,
20358e710227SColy Li 	 * if check_state->enough is non-zero, it means current
20368e710227SColy Li 	 * running check threads are enough, unncessary to create
20378e710227SColy Li 	 * more.
20388e710227SColy Li 	 */
20398e710227SColy Li 	for (i = 0; i < check_state->total_threads; i++) {
20408e710227SColy Li 		/* fetch latest check_state->enough earlier */
2041eb9b6666SColy Li 		smp_mb__before_atomic();
20428e710227SColy Li 		if (atomic_read(&check_state->enough))
20438e710227SColy Li 			break;
20448e710227SColy Li 
20458e710227SColy Li 		check_state->infos[i].result = 0;
20468e710227SColy Li 		check_state->infos[i].state = check_state;
20478e710227SColy Li 		snprintf(name, sizeof(name), "bch_btrchk[%u]", i);
20488e710227SColy Li 		atomic_inc(&check_state->started);
20498e710227SColy Li 
20508e710227SColy Li 		check_state->infos[i].thread =
20518e710227SColy Li 			kthread_run(bch_btree_check_thread,
20528e710227SColy Li 				    &check_state->infos[i],
20538e710227SColy Li 				    name);
20548e710227SColy Li 		if (IS_ERR(check_state->infos[i].thread)) {
205546f5aa88SJoe Perches 			pr_err("fails to run thread bch_btrchk[%d]\n", i);
20568e710227SColy Li 			for (--i; i >= 0; i--)
20578e710227SColy Li 				kthread_stop(check_state->infos[i].thread);
20588e710227SColy Li 			ret = -ENOMEM;
20598e710227SColy Li 			goto out;
20608e710227SColy Li 		}
20618e710227SColy Li 	}
20628e710227SColy Li 
20638e710227SColy Li 	wait_event_interruptible(check_state->wait,
20648e710227SColy Li 				 atomic_read(&check_state->started) == 0 ||
20658e710227SColy Li 				  test_bit(CACHE_SET_IO_DISABLE, &c->flags));
20668e710227SColy Li 
20678e710227SColy Li 	for (i = 0; i < check_state->total_threads; i++) {
20688e710227SColy Li 		if (check_state->infos[i].result) {
20698e710227SColy Li 			ret = check_state->infos[i].result;
20708e710227SColy Li 			goto out;
20718e710227SColy Li 		}
20728e710227SColy Li 	}
20738e710227SColy Li 
20748e710227SColy Li out:
20758e710227SColy Li 	kfree(check_state);
20768e710227SColy Li 	return ret;
2077cafe5635SKent Overstreet }
2078cafe5635SKent Overstreet 
20792531d9eeSKent Overstreet void bch_initial_gc_finish(struct cache_set *c)
20802531d9eeSKent Overstreet {
208108fdb2cdSColy Li 	struct cache *ca = c->cache;
20822531d9eeSKent Overstreet 	struct bucket *b;
20832531d9eeSKent Overstreet 
20842531d9eeSKent Overstreet 	bch_btree_gc_finish(c);
20852531d9eeSKent Overstreet 
20862531d9eeSKent Overstreet 	mutex_lock(&c->bucket_lock);
20872531d9eeSKent Overstreet 
20882531d9eeSKent Overstreet 	/*
20892531d9eeSKent Overstreet 	 * We need to put some unused buckets directly on the prio freelist in
20902531d9eeSKent Overstreet 	 * order to get the allocator thread started - it needs freed buckets in
20912531d9eeSKent Overstreet 	 * order to rewrite the prios and gens, and it needs to rewrite prios
20922531d9eeSKent Overstreet 	 * and gens in order to free buckets.
20932531d9eeSKent Overstreet 	 *
20942531d9eeSKent Overstreet 	 * This is only safe for buckets that have no live data in them, which
20952531d9eeSKent Overstreet 	 * there should always be some of.
20962531d9eeSKent Overstreet 	 */
20972531d9eeSKent Overstreet 	for_each_bucket(b, ca) {
2098682811b3STang Junhui 		if (fifo_full(&ca->free[RESERVE_PRIO]) &&
2099682811b3STang Junhui 		    fifo_full(&ca->free[RESERVE_BTREE]))
21002531d9eeSKent Overstreet 			break;
21012531d9eeSKent Overstreet 
21022531d9eeSKent Overstreet 		if (bch_can_invalidate_bucket(ca, b) &&
21032531d9eeSKent Overstreet 		    !GC_MARK(b)) {
21042531d9eeSKent Overstreet 			__bch_invalidate_one_bucket(ca, b);
2105682811b3STang Junhui 			if (!fifo_push(&ca->free[RESERVE_PRIO],
2106682811b3STang Junhui 			   b - ca->buckets))
2107682811b3STang Junhui 				fifo_push(&ca->free[RESERVE_BTREE],
21082531d9eeSKent Overstreet 					  b - ca->buckets);
21092531d9eeSKent Overstreet 		}
21102531d9eeSKent Overstreet 	}
21112531d9eeSKent Overstreet 
21122531d9eeSKent Overstreet 	mutex_unlock(&c->bucket_lock);
21132531d9eeSKent Overstreet }
21142531d9eeSKent Overstreet 
2115cafe5635SKent Overstreet /* Btree insertion */
2116cafe5635SKent Overstreet 
2117829a60b9SKent Overstreet static bool btree_insert_key(struct btree *b, struct bkey *k,
21181b207d80SKent Overstreet 			     struct bkey *replace_key)
2119cafe5635SKent Overstreet {
21206f10f7d1SColy Li 	unsigned int status;
2121cafe5635SKent Overstreet 
2122cafe5635SKent Overstreet 	BUG_ON(bkey_cmp(k, &b->key) > 0);
2123cafe5635SKent Overstreet 
2124829a60b9SKent Overstreet 	status = bch_btree_insert_key(&b->keys, k, replace_key);
2125829a60b9SKent Overstreet 	if (status != BTREE_INSERT_STATUS_NO_INSERT) {
2126dc9d98d6SKent Overstreet 		bch_check_keys(&b->keys, "%u for %s", status,
21271b207d80SKent Overstreet 			       replace_key ? "replace" : "insert");
2128cafe5635SKent Overstreet 
2129829a60b9SKent Overstreet 		trace_bcache_btree_insert_key(b, k, replace_key != NULL,
2130829a60b9SKent Overstreet 					      status);
2131cafe5635SKent Overstreet 		return true;
2132829a60b9SKent Overstreet 	} else
2133829a60b9SKent Overstreet 		return false;
2134cafe5635SKent Overstreet }
2135cafe5635SKent Overstreet 
213659158fdeSKent Overstreet static size_t insert_u64s_remaining(struct btree *b)
213759158fdeSKent Overstreet {
21383572324aSKent Overstreet 	long ret = bch_btree_keys_u64s_remaining(&b->keys);
213959158fdeSKent Overstreet 
214059158fdeSKent Overstreet 	/*
214159158fdeSKent Overstreet 	 * Might land in the middle of an existing extent and have to split it
214259158fdeSKent Overstreet 	 */
214359158fdeSKent Overstreet 	if (b->keys.ops->is_extents)
214459158fdeSKent Overstreet 		ret -= KEY_MAX_U64S;
214559158fdeSKent Overstreet 
214659158fdeSKent Overstreet 	return max(ret, 0L);
214759158fdeSKent Overstreet }
214859158fdeSKent Overstreet 
214926c949f8SKent Overstreet static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
21501b207d80SKent Overstreet 				  struct keylist *insert_keys,
21511b207d80SKent Overstreet 				  struct bkey *replace_key)
2152cafe5635SKent Overstreet {
2153cafe5635SKent Overstreet 	bool ret = false;
2154dc9d98d6SKent Overstreet 	int oldsize = bch_count_data(&b->keys);
2155cafe5635SKent Overstreet 
215626c949f8SKent Overstreet 	while (!bch_keylist_empty(insert_keys)) {
2157c2f95ae2SKent Overstreet 		struct bkey *k = insert_keys->keys;
215826c949f8SKent Overstreet 
215959158fdeSKent Overstreet 		if (bkey_u64s(k) > insert_u64s_remaining(b))
2160403b6cdeSKent Overstreet 			break;
2161403b6cdeSKent Overstreet 
2162403b6cdeSKent Overstreet 		if (bkey_cmp(k, &b->key) <= 0) {
21633a3b6a4eSKent Overstreet 			if (!b->level)
21643a3b6a4eSKent Overstreet 				bkey_put(b->c, k);
216526c949f8SKent Overstreet 
2166829a60b9SKent Overstreet 			ret |= btree_insert_key(b, k, replace_key);
216726c949f8SKent Overstreet 			bch_keylist_pop_front(insert_keys);
216826c949f8SKent Overstreet 		} else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
216926c949f8SKent Overstreet 			BKEY_PADDED(key) temp;
2170c2f95ae2SKent Overstreet 			bkey_copy(&temp.key, insert_keys->keys);
217126c949f8SKent Overstreet 
217226c949f8SKent Overstreet 			bch_cut_back(&b->key, &temp.key);
2173c2f95ae2SKent Overstreet 			bch_cut_front(&b->key, insert_keys->keys);
217426c949f8SKent Overstreet 
2175829a60b9SKent Overstreet 			ret |= btree_insert_key(b, &temp.key, replace_key);
217626c949f8SKent Overstreet 			break;
217726c949f8SKent Overstreet 		} else {
217826c949f8SKent Overstreet 			break;
217926c949f8SKent Overstreet 		}
2180cafe5635SKent Overstreet 	}
2181cafe5635SKent Overstreet 
2182829a60b9SKent Overstreet 	if (!ret)
2183829a60b9SKent Overstreet 		op->insert_collision = true;
2184829a60b9SKent Overstreet 
2185403b6cdeSKent Overstreet 	BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
2186403b6cdeSKent Overstreet 
2187dc9d98d6SKent Overstreet 	BUG_ON(bch_count_data(&b->keys) < oldsize);
2188cafe5635SKent Overstreet 	return ret;
2189cafe5635SKent Overstreet }
2190cafe5635SKent Overstreet 
219126c949f8SKent Overstreet static int btree_split(struct btree *b, struct btree_op *op,
219226c949f8SKent Overstreet 		       struct keylist *insert_keys,
21931b207d80SKent Overstreet 		       struct bkey *replace_key)
2194cafe5635SKent Overstreet {
2195d6fd3b11SKent Overstreet 	bool split;
2196cafe5635SKent Overstreet 	struct btree *n1, *n2 = NULL, *n3 = NULL;
2197cafe5635SKent Overstreet 	uint64_t start_time = local_clock();
2198b54d6934SKent Overstreet 	struct closure cl;
219917e21a9fSKent Overstreet 	struct keylist parent_keys;
2200b54d6934SKent Overstreet 
2201b54d6934SKent Overstreet 	closure_init_stack(&cl);
220217e21a9fSKent Overstreet 	bch_keylist_init(&parent_keys);
2203cafe5635SKent Overstreet 
22040a63b66dSKent Overstreet 	if (btree_check_reserve(b, op)) {
22050a63b66dSKent Overstreet 		if (!b->level)
220678365411SKent Overstreet 			return -EINTR;
22070a63b66dSKent Overstreet 		else
22080a63b66dSKent Overstreet 			WARN(1, "insufficient reserve for split\n");
22090a63b66dSKent Overstreet 	}
221078365411SKent Overstreet 
22110a63b66dSKent Overstreet 	n1 = btree_node_alloc_replacement(b, op);
2212cafe5635SKent Overstreet 	if (IS_ERR(n1))
2213cafe5635SKent Overstreet 		goto err;
2214cafe5635SKent Overstreet 
2215ee811287SKent Overstreet 	split = set_blocks(btree_bset_first(n1),
22164e1ebae3SColy Li 			   block_bytes(n1->c->cache)) > (btree_blocks(b) * 4) / 5;
2217cafe5635SKent Overstreet 
2218cafe5635SKent Overstreet 	if (split) {
22196f10f7d1SColy Li 		unsigned int keys = 0;
2220cafe5635SKent Overstreet 
2221ee811287SKent Overstreet 		trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
2222c37511b8SKent Overstreet 
22232452cc89SSlava Pestov 		n2 = bch_btree_node_alloc(b->c, op, b->level, b->parent);
2224cafe5635SKent Overstreet 		if (IS_ERR(n2))
2225cafe5635SKent Overstreet 			goto err_free1;
2226cafe5635SKent Overstreet 
2227d6fd3b11SKent Overstreet 		if (!b->parent) {
22282452cc89SSlava Pestov 			n3 = bch_btree_node_alloc(b->c, op, b->level + 1, NULL);
2229cafe5635SKent Overstreet 			if (IS_ERR(n3))
2230cafe5635SKent Overstreet 				goto err_free2;
2231cafe5635SKent Overstreet 		}
2232cafe5635SKent Overstreet 
22332a285686SKent Overstreet 		mutex_lock(&n1->write_lock);
22342a285686SKent Overstreet 		mutex_lock(&n2->write_lock);
22352a285686SKent Overstreet 
22361b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2237cafe5635SKent Overstreet 
2238d6fd3b11SKent Overstreet 		/*
2239d6fd3b11SKent Overstreet 		 * Has to be a linear search because we don't have an auxiliary
2240cafe5635SKent Overstreet 		 * search tree yet
2241cafe5635SKent Overstreet 		 */
2242cafe5635SKent Overstreet 
2243ee811287SKent Overstreet 		while (keys < (btree_bset_first(n1)->keys * 3) / 5)
2244ee811287SKent Overstreet 			keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
2245fafff81cSKent Overstreet 							keys));
2246cafe5635SKent Overstreet 
2247fafff81cSKent Overstreet 		bkey_copy_key(&n1->key,
2248ee811287SKent Overstreet 			      bset_bkey_idx(btree_bset_first(n1), keys));
2249ee811287SKent Overstreet 		keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
2250cafe5635SKent Overstreet 
2251ee811287SKent Overstreet 		btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
2252ee811287SKent Overstreet 		btree_bset_first(n1)->keys = keys;
2253cafe5635SKent Overstreet 
2254ee811287SKent Overstreet 		memcpy(btree_bset_first(n2)->start,
2255ee811287SKent Overstreet 		       bset_bkey_last(btree_bset_first(n1)),
2256ee811287SKent Overstreet 		       btree_bset_first(n2)->keys * sizeof(uint64_t));
2257cafe5635SKent Overstreet 
2258cafe5635SKent Overstreet 		bkey_copy_key(&n2->key, &b->key);
2259cafe5635SKent Overstreet 
226017e21a9fSKent Overstreet 		bch_keylist_add(&parent_keys, &n2->key);
2261b54d6934SKent Overstreet 		bch_btree_node_write(n2, &cl);
22622a285686SKent Overstreet 		mutex_unlock(&n2->write_lock);
2263cafe5635SKent Overstreet 		rw_unlock(true, n2);
2264c37511b8SKent Overstreet 	} else {
2265ee811287SKent Overstreet 		trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
2266c37511b8SKent Overstreet 
22672a285686SKent Overstreet 		mutex_lock(&n1->write_lock);
22681b207d80SKent Overstreet 		bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2269c37511b8SKent Overstreet 	}
2270cafe5635SKent Overstreet 
227117e21a9fSKent Overstreet 	bch_keylist_add(&parent_keys, &n1->key);
2272b54d6934SKent Overstreet 	bch_btree_node_write(n1, &cl);
22732a285686SKent Overstreet 	mutex_unlock(&n1->write_lock);
2274cafe5635SKent Overstreet 
2275cafe5635SKent Overstreet 	if (n3) {
2276d6fd3b11SKent Overstreet 		/* Depth increases, make a new root */
22772a285686SKent Overstreet 		mutex_lock(&n3->write_lock);
2278cafe5635SKent Overstreet 		bkey_copy_key(&n3->key, &MAX_KEY);
227917e21a9fSKent Overstreet 		bch_btree_insert_keys(n3, op, &parent_keys, NULL);
2280b54d6934SKent Overstreet 		bch_btree_node_write(n3, &cl);
22812a285686SKent Overstreet 		mutex_unlock(&n3->write_lock);
2282cafe5635SKent Overstreet 
2283b54d6934SKent Overstreet 		closure_sync(&cl);
2284cafe5635SKent Overstreet 		bch_btree_set_root(n3);
2285cafe5635SKent Overstreet 		rw_unlock(true, n3);
2286d6fd3b11SKent Overstreet 	} else if (!b->parent) {
2287d6fd3b11SKent Overstreet 		/* Root filled up but didn't need to be split */
2288b54d6934SKent Overstreet 		closure_sync(&cl);
2289cafe5635SKent Overstreet 		bch_btree_set_root(n1);
2290cafe5635SKent Overstreet 	} else {
229117e21a9fSKent Overstreet 		/* Split a non root node */
2292b54d6934SKent Overstreet 		closure_sync(&cl);
229317e21a9fSKent Overstreet 		make_btree_freeing_key(b, parent_keys.top);
229417e21a9fSKent Overstreet 		bch_keylist_push(&parent_keys);
229517e21a9fSKent Overstreet 
229617e21a9fSKent Overstreet 		bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
229717e21a9fSKent Overstreet 		BUG_ON(!bch_keylist_empty(&parent_keys));
2298cafe5635SKent Overstreet 	}
2299cafe5635SKent Overstreet 
230005335cffSKent Overstreet 	btree_node_free(b);
2301cafe5635SKent Overstreet 	rw_unlock(true, n1);
2302cafe5635SKent Overstreet 
2303169ef1cfSKent Overstreet 	bch_time_stats_update(&b->c->btree_split_time, start_time);
2304cafe5635SKent Overstreet 
2305cafe5635SKent Overstreet 	return 0;
2306cafe5635SKent Overstreet err_free2:
23075f5837d2SKent Overstreet 	bkey_put(b->c, &n2->key);
2308e8e1d468SKent Overstreet 	btree_node_free(n2);
2309cafe5635SKent Overstreet 	rw_unlock(true, n2);
2310cafe5635SKent Overstreet err_free1:
23115f5837d2SKent Overstreet 	bkey_put(b->c, &n1->key);
2312e8e1d468SKent Overstreet 	btree_node_free(n1);
2313cafe5635SKent Overstreet 	rw_unlock(true, n1);
2314cafe5635SKent Overstreet err:
23150a63b66dSKent Overstreet 	WARN(1, "bcache: btree split failed (level %u)", b->level);
23165f5837d2SKent Overstreet 
2317cafe5635SKent Overstreet 	if (n3 == ERR_PTR(-EAGAIN) ||
2318cafe5635SKent Overstreet 	    n2 == ERR_PTR(-EAGAIN) ||
2319cafe5635SKent Overstreet 	    n1 == ERR_PTR(-EAGAIN))
2320cafe5635SKent Overstreet 		return -EAGAIN;
2321cafe5635SKent Overstreet 
2322cafe5635SKent Overstreet 	return -ENOMEM;
2323cafe5635SKent Overstreet }
2324cafe5635SKent Overstreet 
232526c949f8SKent Overstreet static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2326c18536a7SKent Overstreet 				 struct keylist *insert_keys,
23271b207d80SKent Overstreet 				 atomic_t *journal_ref,
23281b207d80SKent Overstreet 				 struct bkey *replace_key)
232926c949f8SKent Overstreet {
23302a285686SKent Overstreet 	struct closure cl;
23312a285686SKent Overstreet 
23321b207d80SKent Overstreet 	BUG_ON(b->level && replace_key);
23331b207d80SKent Overstreet 
23342a285686SKent Overstreet 	closure_init_stack(&cl);
23352a285686SKent Overstreet 
23362a285686SKent Overstreet 	mutex_lock(&b->write_lock);
23372a285686SKent Overstreet 
23382a285686SKent Overstreet 	if (write_block(b) != btree_bset_last(b) &&
23392a285686SKent Overstreet 	    b->keys.last_set_unwritten)
23402a285686SKent Overstreet 		bch_btree_init_next(b); /* just wrote a set */
23412a285686SKent Overstreet 
234259158fdeSKent Overstreet 	if (bch_keylist_nkeys(insert_keys) > insert_u64s_remaining(b)) {
23432a285686SKent Overstreet 		mutex_unlock(&b->write_lock);
23442a285686SKent Overstreet 		goto split;
23452a285686SKent Overstreet 	}
23462a285686SKent Overstreet 
23472a285686SKent Overstreet 	BUG_ON(write_block(b) != btree_bset_last(b));
23482a285686SKent Overstreet 
23492a285686SKent Overstreet 	if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
23502a285686SKent Overstreet 		if (!b->level)
23512a285686SKent Overstreet 			bch_btree_leaf_dirty(b, journal_ref);
23522a285686SKent Overstreet 		else
23532a285686SKent Overstreet 			bch_btree_node_write(b, &cl);
23542a285686SKent Overstreet 	}
23552a285686SKent Overstreet 
23562a285686SKent Overstreet 	mutex_unlock(&b->write_lock);
23572a285686SKent Overstreet 
23582a285686SKent Overstreet 	/* wait for btree node write if necessary, after unlock */
23592a285686SKent Overstreet 	closure_sync(&cl);
23602a285686SKent Overstreet 
23612a285686SKent Overstreet 	return 0;
23622a285686SKent Overstreet split:
236326c949f8SKent Overstreet 	if (current->bio_list) {
236426c949f8SKent Overstreet 		op->lock = b->c->root->level + 1;
236517e21a9fSKent Overstreet 		return -EAGAIN;
236626c949f8SKent Overstreet 	} else if (op->lock <= b->c->root->level) {
236726c949f8SKent Overstreet 		op->lock = b->c->root->level + 1;
236817e21a9fSKent Overstreet 		return -EINTR;
236926c949f8SKent Overstreet 	} else {
237017e21a9fSKent Overstreet 		/* Invalidated all iterators */
23713b3e9e50SKent Overstreet 		int ret = btree_split(b, op, insert_keys, replace_key);
23723b3e9e50SKent Overstreet 
23732a285686SKent Overstreet 		if (bch_keylist_empty(insert_keys))
237417e21a9fSKent Overstreet 			return 0;
23752a285686SKent Overstreet 		else if (!ret)
23762a285686SKent Overstreet 			return -EINTR;
23772a285686SKent Overstreet 		return ret;
237817e21a9fSKent Overstreet 	}
237926c949f8SKent Overstreet }
238026c949f8SKent Overstreet 
2381e7c590ebSKent Overstreet int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2382e7c590ebSKent Overstreet 			       struct bkey *check_key)
2383e7c590ebSKent Overstreet {
2384e7c590ebSKent Overstreet 	int ret = -EINTR;
2385e7c590ebSKent Overstreet 	uint64_t btree_ptr = b->key.ptr[0];
2386e7c590ebSKent Overstreet 	unsigned long seq = b->seq;
2387e7c590ebSKent Overstreet 	struct keylist insert;
2388e7c590ebSKent Overstreet 	bool upgrade = op->lock == -1;
2389e7c590ebSKent Overstreet 
2390e7c590ebSKent Overstreet 	bch_keylist_init(&insert);
2391e7c590ebSKent Overstreet 
2392e7c590ebSKent Overstreet 	if (upgrade) {
2393e7c590ebSKent Overstreet 		rw_unlock(false, b);
2394e7c590ebSKent Overstreet 		rw_lock(true, b, b->level);
2395e7c590ebSKent Overstreet 
2396e7c590ebSKent Overstreet 		if (b->key.ptr[0] != btree_ptr ||
23972ef9ccbfSZheng Liu 		    b->seq != seq + 1) {
23982ef9ccbfSZheng Liu 			op->lock = b->level;
2399e7c590ebSKent Overstreet 			goto out;
2400e7c590ebSKent Overstreet 		}
24012ef9ccbfSZheng Liu 	}
2402e7c590ebSKent Overstreet 
2403e7c590ebSKent Overstreet 	SET_KEY_PTRS(check_key, 1);
2404e7c590ebSKent Overstreet 	get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2405e7c590ebSKent Overstreet 
2406e7c590ebSKent Overstreet 	SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2407e7c590ebSKent Overstreet 
2408e7c590ebSKent Overstreet 	bch_keylist_add(&insert, check_key);
2409e7c590ebSKent Overstreet 
24101b207d80SKent Overstreet 	ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2411e7c590ebSKent Overstreet 
2412e7c590ebSKent Overstreet 	BUG_ON(!ret && !bch_keylist_empty(&insert));
2413e7c590ebSKent Overstreet out:
2414e7c590ebSKent Overstreet 	if (upgrade)
2415e7c590ebSKent Overstreet 		downgrade_write(&b->lock);
2416e7c590ebSKent Overstreet 	return ret;
2417e7c590ebSKent Overstreet }
2418e7c590ebSKent Overstreet 
2419cc7b8819SKent Overstreet struct btree_insert_op {
2420cc7b8819SKent Overstreet 	struct btree_op	op;
2421cc7b8819SKent Overstreet 	struct keylist	*keys;
2422cc7b8819SKent Overstreet 	atomic_t	*journal_ref;
2423cc7b8819SKent Overstreet 	struct bkey	*replace_key;
2424cc7b8819SKent Overstreet };
2425cc7b8819SKent Overstreet 
242608239ca2SWei Yongjun static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2427cafe5635SKent Overstreet {
2428cc7b8819SKent Overstreet 	struct btree_insert_op *op = container_of(b_op,
2429cc7b8819SKent Overstreet 					struct btree_insert_op, op);
2430403b6cdeSKent Overstreet 
2431cc7b8819SKent Overstreet 	int ret = bch_btree_insert_node(b, &op->op, op->keys,
2432cc7b8819SKent Overstreet 					op->journal_ref, op->replace_key);
2433cc7b8819SKent Overstreet 	if (ret && !bch_keylist_empty(op->keys))
2434cc7b8819SKent Overstreet 		return ret;
2435cc7b8819SKent Overstreet 	else
2436cc7b8819SKent Overstreet 		return MAP_DONE;
2437cafe5635SKent Overstreet }
2438cafe5635SKent Overstreet 
2439cc7b8819SKent Overstreet int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2440cc7b8819SKent Overstreet 		     atomic_t *journal_ref, struct bkey *replace_key)
2441cafe5635SKent Overstreet {
2442cc7b8819SKent Overstreet 	struct btree_insert_op op;
2443cafe5635SKent Overstreet 	int ret = 0;
2444cafe5635SKent Overstreet 
2445cc7b8819SKent Overstreet 	BUG_ON(current->bio_list);
24464f3d4014SKent Overstreet 	BUG_ON(bch_keylist_empty(keys));
2447cafe5635SKent Overstreet 
2448cc7b8819SKent Overstreet 	bch_btree_op_init(&op.op, 0);
2449cc7b8819SKent Overstreet 	op.keys		= keys;
2450cc7b8819SKent Overstreet 	op.journal_ref	= journal_ref;
2451cc7b8819SKent Overstreet 	op.replace_key	= replace_key;
2452cafe5635SKent Overstreet 
2453cc7b8819SKent Overstreet 	while (!ret && !bch_keylist_empty(keys)) {
2454cc7b8819SKent Overstreet 		op.op.lock = 0;
2455cc7b8819SKent Overstreet 		ret = bch_btree_map_leaf_nodes(&op.op, c,
2456cc7b8819SKent Overstreet 					       &START_KEY(keys->keys),
2457cc7b8819SKent Overstreet 					       btree_insert_fn);
2458cc7b8819SKent Overstreet 	}
2459cc7b8819SKent Overstreet 
2460cc7b8819SKent Overstreet 	if (ret) {
2461cafe5635SKent Overstreet 		struct bkey *k;
2462cafe5635SKent Overstreet 
246346f5aa88SJoe Perches 		pr_err("error %i\n", ret);
2464cafe5635SKent Overstreet 
24654f3d4014SKent Overstreet 		while ((k = bch_keylist_pop(keys)))
24663a3b6a4eSKent Overstreet 			bkey_put(c, k);
2467cc7b8819SKent Overstreet 	} else if (op.op.insert_collision)
2468cc7b8819SKent Overstreet 		ret = -ESRCH;
24696054c6d4SKent Overstreet 
2470cafe5635SKent Overstreet 	return ret;
2471cafe5635SKent Overstreet }
2472cafe5635SKent Overstreet 
2473cafe5635SKent Overstreet void bch_btree_set_root(struct btree *b)
2474cafe5635SKent Overstreet {
24756f10f7d1SColy Li 	unsigned int i;
2476e49c7c37SKent Overstreet 	struct closure cl;
2477e49c7c37SKent Overstreet 
2478e49c7c37SKent Overstreet 	closure_init_stack(&cl);
2479cafe5635SKent Overstreet 
2480c37511b8SKent Overstreet 	trace_bcache_btree_set_root(b);
2481c37511b8SKent Overstreet 
2482cafe5635SKent Overstreet 	BUG_ON(!b->written);
2483cafe5635SKent Overstreet 
2484cafe5635SKent Overstreet 	for (i = 0; i < KEY_PTRS(&b->key); i++)
2485cafe5635SKent Overstreet 		BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2486cafe5635SKent Overstreet 
2487cafe5635SKent Overstreet 	mutex_lock(&b->c->bucket_lock);
2488cafe5635SKent Overstreet 	list_del_init(&b->list);
2489cafe5635SKent Overstreet 	mutex_unlock(&b->c->bucket_lock);
2490cafe5635SKent Overstreet 
2491cafe5635SKent Overstreet 	b->c->root = b;
2492cafe5635SKent Overstreet 
2493e49c7c37SKent Overstreet 	bch_journal_meta(b->c, &cl);
2494e49c7c37SKent Overstreet 	closure_sync(&cl);
2495cafe5635SKent Overstreet }
2496cafe5635SKent Overstreet 
249748dad8baSKent Overstreet /* Map across nodes or keys */
249848dad8baSKent Overstreet 
249948dad8baSKent Overstreet static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
250048dad8baSKent Overstreet 				       struct bkey *from,
250148dad8baSKent Overstreet 				       btree_map_nodes_fn *fn, int flags)
250248dad8baSKent Overstreet {
250348dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
250448dad8baSKent Overstreet 
250548dad8baSKent Overstreet 	if (b->level) {
250648dad8baSKent Overstreet 		struct bkey *k;
250748dad8baSKent Overstreet 		struct btree_iter iter;
250848dad8baSKent Overstreet 
2509c052dd9aSKent Overstreet 		bch_btree_iter_init(&b->keys, &iter, from);
251048dad8baSKent Overstreet 
2511a85e968eSKent Overstreet 		while ((k = bch_btree_iter_next_filter(&iter, &b->keys,
251248dad8baSKent Overstreet 						       bch_ptr_bad))) {
2513feac1a70SColy Li 			ret = bcache_btree(map_nodes_recurse, k, b,
251448dad8baSKent Overstreet 				    op, from, fn, flags);
251548dad8baSKent Overstreet 			from = NULL;
251648dad8baSKent Overstreet 
251748dad8baSKent Overstreet 			if (ret != MAP_CONTINUE)
251848dad8baSKent Overstreet 				return ret;
251948dad8baSKent Overstreet 		}
252048dad8baSKent Overstreet 	}
252148dad8baSKent Overstreet 
252248dad8baSKent Overstreet 	if (!b->level || flags == MAP_ALL_NODES)
252348dad8baSKent Overstreet 		ret = fn(op, b);
252448dad8baSKent Overstreet 
252548dad8baSKent Overstreet 	return ret;
252648dad8baSKent Overstreet }
252748dad8baSKent Overstreet 
252848dad8baSKent Overstreet int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
252948dad8baSKent Overstreet 			  struct bkey *from, btree_map_nodes_fn *fn, int flags)
253048dad8baSKent Overstreet {
2531feac1a70SColy Li 	return bcache_btree_root(map_nodes_recurse, c, op, from, fn, flags);
253248dad8baSKent Overstreet }
253348dad8baSKent Overstreet 
2534253a99d9SColy Li int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
253548dad8baSKent Overstreet 				      struct bkey *from, btree_map_keys_fn *fn,
253648dad8baSKent Overstreet 				      int flags)
253748dad8baSKent Overstreet {
253848dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
253948dad8baSKent Overstreet 	struct bkey *k;
254048dad8baSKent Overstreet 	struct btree_iter iter;
254148dad8baSKent Overstreet 
2542c052dd9aSKent Overstreet 	bch_btree_iter_init(&b->keys, &iter, from);
254348dad8baSKent Overstreet 
2544a85e968eSKent Overstreet 	while ((k = bch_btree_iter_next_filter(&iter, &b->keys, bch_ptr_bad))) {
254548dad8baSKent Overstreet 		ret = !b->level
254648dad8baSKent Overstreet 			? fn(op, b, k)
2547feac1a70SColy Li 			: bcache_btree(map_keys_recurse, k,
2548feac1a70SColy Li 				       b, op, from, fn, flags);
254948dad8baSKent Overstreet 		from = NULL;
255048dad8baSKent Overstreet 
255148dad8baSKent Overstreet 		if (ret != MAP_CONTINUE)
255248dad8baSKent Overstreet 			return ret;
255348dad8baSKent Overstreet 	}
255448dad8baSKent Overstreet 
255548dad8baSKent Overstreet 	if (!b->level && (flags & MAP_END_KEY))
255648dad8baSKent Overstreet 		ret = fn(op, b, &KEY(KEY_INODE(&b->key),
255748dad8baSKent Overstreet 				     KEY_OFFSET(&b->key), 0));
255848dad8baSKent Overstreet 
255948dad8baSKent Overstreet 	return ret;
256048dad8baSKent Overstreet }
256148dad8baSKent Overstreet 
256248dad8baSKent Overstreet int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
256348dad8baSKent Overstreet 		       struct bkey *from, btree_map_keys_fn *fn, int flags)
256448dad8baSKent Overstreet {
2565feac1a70SColy Li 	return bcache_btree_root(map_keys_recurse, c, op, from, fn, flags);
256648dad8baSKent Overstreet }
256748dad8baSKent Overstreet 
2568cafe5635SKent Overstreet /* Keybuf code */
2569cafe5635SKent Overstreet 
2570cafe5635SKent Overstreet static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2571cafe5635SKent Overstreet {
2572cafe5635SKent Overstreet 	/* Overlapping keys compare equal */
2573cafe5635SKent Overstreet 	if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2574cafe5635SKent Overstreet 		return -1;
2575cafe5635SKent Overstreet 	if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2576cafe5635SKent Overstreet 		return 1;
2577cafe5635SKent Overstreet 	return 0;
2578cafe5635SKent Overstreet }
2579cafe5635SKent Overstreet 
2580cafe5635SKent Overstreet static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2581cafe5635SKent Overstreet 					    struct keybuf_key *r)
2582cafe5635SKent Overstreet {
2583cafe5635SKent Overstreet 	return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2584cafe5635SKent Overstreet }
2585cafe5635SKent Overstreet 
258648dad8baSKent Overstreet struct refill {
258748dad8baSKent Overstreet 	struct btree_op	op;
25886f10f7d1SColy Li 	unsigned int	nr_found;
258948dad8baSKent Overstreet 	struct keybuf	*buf;
259048dad8baSKent Overstreet 	struct bkey	*end;
259148dad8baSKent Overstreet 	keybuf_pred_fn	*pred;
259248dad8baSKent Overstreet };
259348dad8baSKent Overstreet 
259448dad8baSKent Overstreet static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
259548dad8baSKent Overstreet 			    struct bkey *k)
2596cafe5635SKent Overstreet {
259748dad8baSKent Overstreet 	struct refill *refill = container_of(op, struct refill, op);
259848dad8baSKent Overstreet 	struct keybuf *buf = refill->buf;
259948dad8baSKent Overstreet 	int ret = MAP_CONTINUE;
2600cafe5635SKent Overstreet 
26012d6cb6edSTang Junhui 	if (bkey_cmp(k, refill->end) > 0) {
260248dad8baSKent Overstreet 		ret = MAP_DONE;
260348dad8baSKent Overstreet 		goto out;
2604cafe5635SKent Overstreet 	}
2605cafe5635SKent Overstreet 
260648dad8baSKent Overstreet 	if (!KEY_SIZE(k)) /* end key */
260748dad8baSKent Overstreet 		goto out;
2608cafe5635SKent Overstreet 
260948dad8baSKent Overstreet 	if (refill->pred(buf, k)) {
2610cafe5635SKent Overstreet 		struct keybuf_key *w;
2611cafe5635SKent Overstreet 
2612cafe5635SKent Overstreet 		spin_lock(&buf->lock);
2613cafe5635SKent Overstreet 
2614cafe5635SKent Overstreet 		w = array_alloc(&buf->freelist);
261548dad8baSKent Overstreet 		if (!w) {
261648dad8baSKent Overstreet 			spin_unlock(&buf->lock);
261748dad8baSKent Overstreet 			return MAP_DONE;
261848dad8baSKent Overstreet 		}
2619cafe5635SKent Overstreet 
2620cafe5635SKent Overstreet 		w->private = NULL;
2621cafe5635SKent Overstreet 		bkey_copy(&w->key, k);
2622cafe5635SKent Overstreet 
2623cafe5635SKent Overstreet 		if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2624cafe5635SKent Overstreet 			array_free(&buf->freelist, w);
262548a915a8SKent Overstreet 		else
262648a915a8SKent Overstreet 			refill->nr_found++;
2627cafe5635SKent Overstreet 
262848dad8baSKent Overstreet 		if (array_freelist_empty(&buf->freelist))
262948dad8baSKent Overstreet 			ret = MAP_DONE;
263048dad8baSKent Overstreet 
2631cafe5635SKent Overstreet 		spin_unlock(&buf->lock);
2632cafe5635SKent Overstreet 	}
263348dad8baSKent Overstreet out:
263448dad8baSKent Overstreet 	buf->last_scanned = *k;
263548dad8baSKent Overstreet 	return ret;
2636cafe5635SKent Overstreet }
2637cafe5635SKent Overstreet 
2638cafe5635SKent Overstreet void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
263972c27061SKent Overstreet 		       struct bkey *end, keybuf_pred_fn *pred)
2640cafe5635SKent Overstreet {
2641cafe5635SKent Overstreet 	struct bkey start = buf->last_scanned;
264248dad8baSKent Overstreet 	struct refill refill;
2643cafe5635SKent Overstreet 
2644cafe5635SKent Overstreet 	cond_resched();
2645cafe5635SKent Overstreet 
2646b54d6934SKent Overstreet 	bch_btree_op_init(&refill.op, -1);
264748a915a8SKent Overstreet 	refill.nr_found	= 0;
264848dad8baSKent Overstreet 	refill.buf	= buf;
264948dad8baSKent Overstreet 	refill.end	= end;
265048dad8baSKent Overstreet 	refill.pred	= pred;
265148dad8baSKent Overstreet 
265248dad8baSKent Overstreet 	bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
265348dad8baSKent Overstreet 			   refill_keybuf_fn, MAP_END_KEY);
2654cafe5635SKent Overstreet 
265548a915a8SKent Overstreet 	trace_bcache_keyscan(refill.nr_found,
2656cafe5635SKent Overstreet 			     KEY_INODE(&start), KEY_OFFSET(&start),
265748a915a8SKent Overstreet 			     KEY_INODE(&buf->last_scanned),
265848a915a8SKent Overstreet 			     KEY_OFFSET(&buf->last_scanned));
2659cafe5635SKent Overstreet 
2660cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2661cafe5635SKent Overstreet 
2662cafe5635SKent Overstreet 	if (!RB_EMPTY_ROOT(&buf->keys)) {
2663cafe5635SKent Overstreet 		struct keybuf_key *w;
26641fae7cf0SColy Li 
2665cafe5635SKent Overstreet 		w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2666cafe5635SKent Overstreet 		buf->start	= START_KEY(&w->key);
2667cafe5635SKent Overstreet 
2668cafe5635SKent Overstreet 		w = RB_LAST(&buf->keys, struct keybuf_key, node);
2669cafe5635SKent Overstreet 		buf->end	= w->key;
2670cafe5635SKent Overstreet 	} else {
2671cafe5635SKent Overstreet 		buf->start	= MAX_KEY;
2672cafe5635SKent Overstreet 		buf->end	= MAX_KEY;
2673cafe5635SKent Overstreet 	}
2674cafe5635SKent Overstreet 
2675cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2676cafe5635SKent Overstreet }
2677cafe5635SKent Overstreet 
2678cafe5635SKent Overstreet static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2679cafe5635SKent Overstreet {
2680cafe5635SKent Overstreet 	rb_erase(&w->node, &buf->keys);
2681cafe5635SKent Overstreet 	array_free(&buf->freelist, w);
2682cafe5635SKent Overstreet }
2683cafe5635SKent Overstreet 
2684cafe5635SKent Overstreet void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2685cafe5635SKent Overstreet {
2686cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2687cafe5635SKent Overstreet 	__bch_keybuf_del(buf, w);
2688cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2689cafe5635SKent Overstreet }
2690cafe5635SKent Overstreet 
2691cafe5635SKent Overstreet bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2692cafe5635SKent Overstreet 				  struct bkey *end)
2693cafe5635SKent Overstreet {
2694cafe5635SKent Overstreet 	bool ret = false;
2695cafe5635SKent Overstreet 	struct keybuf_key *p, *w, s;
26961fae7cf0SColy Li 
2697cafe5635SKent Overstreet 	s.key = *start;
2698cafe5635SKent Overstreet 
2699cafe5635SKent Overstreet 	if (bkey_cmp(end, &buf->start) <= 0 ||
2700cafe5635SKent Overstreet 	    bkey_cmp(start, &buf->end) >= 0)
2701cafe5635SKent Overstreet 		return false;
2702cafe5635SKent Overstreet 
2703cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2704cafe5635SKent Overstreet 	w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2705cafe5635SKent Overstreet 
2706cafe5635SKent Overstreet 	while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2707cafe5635SKent Overstreet 		p = w;
2708cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2709cafe5635SKent Overstreet 
2710cafe5635SKent Overstreet 		if (p->private)
2711cafe5635SKent Overstreet 			ret = true;
2712cafe5635SKent Overstreet 		else
2713cafe5635SKent Overstreet 			__bch_keybuf_del(buf, p);
2714cafe5635SKent Overstreet 	}
2715cafe5635SKent Overstreet 
2716cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2717cafe5635SKent Overstreet 	return ret;
2718cafe5635SKent Overstreet }
2719cafe5635SKent Overstreet 
2720cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2721cafe5635SKent Overstreet {
2722cafe5635SKent Overstreet 	struct keybuf_key *w;
27231fae7cf0SColy Li 
2724cafe5635SKent Overstreet 	spin_lock(&buf->lock);
2725cafe5635SKent Overstreet 
2726cafe5635SKent Overstreet 	w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2727cafe5635SKent Overstreet 
2728cafe5635SKent Overstreet 	while (w && w->private)
2729cafe5635SKent Overstreet 		w = RB_NEXT(w, node);
2730cafe5635SKent Overstreet 
2731cafe5635SKent Overstreet 	if (w)
2732cafe5635SKent Overstreet 		w->private = ERR_PTR(-EINTR);
2733cafe5635SKent Overstreet 
2734cafe5635SKent Overstreet 	spin_unlock(&buf->lock);
2735cafe5635SKent Overstreet 	return w;
2736cafe5635SKent Overstreet }
2737cafe5635SKent Overstreet 
2738cafe5635SKent Overstreet struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2739cafe5635SKent Overstreet 					  struct keybuf *buf,
274072c27061SKent Overstreet 					  struct bkey *end,
274172c27061SKent Overstreet 					  keybuf_pred_fn *pred)
2742cafe5635SKent Overstreet {
2743cafe5635SKent Overstreet 	struct keybuf_key *ret;
2744cafe5635SKent Overstreet 
2745cafe5635SKent Overstreet 	while (1) {
2746cafe5635SKent Overstreet 		ret = bch_keybuf_next(buf);
2747cafe5635SKent Overstreet 		if (ret)
2748cafe5635SKent Overstreet 			break;
2749cafe5635SKent Overstreet 
2750cafe5635SKent Overstreet 		if (bkey_cmp(&buf->last_scanned, end) >= 0) {
275146f5aa88SJoe Perches 			pr_debug("scan finished\n");
2752cafe5635SKent Overstreet 			break;
2753cafe5635SKent Overstreet 		}
2754cafe5635SKent Overstreet 
275572c27061SKent Overstreet 		bch_refill_keybuf(c, buf, end, pred);
2756cafe5635SKent Overstreet 	}
2757cafe5635SKent Overstreet 
2758cafe5635SKent Overstreet 	return ret;
2759cafe5635SKent Overstreet }
2760cafe5635SKent Overstreet 
276172c27061SKent Overstreet void bch_keybuf_init(struct keybuf *buf)
2762cafe5635SKent Overstreet {
2763cafe5635SKent Overstreet 	buf->last_scanned	= MAX_KEY;
2764cafe5635SKent Overstreet 	buf->keys		= RB_ROOT;
2765cafe5635SKent Overstreet 
2766cafe5635SKent Overstreet 	spin_lock_init(&buf->lock);
2767cafe5635SKent Overstreet 	array_allocator_init(&buf->freelist);
2768cafe5635SKent Overstreet }
2769*9f233ffeSKai Krakow 
2770*9f233ffeSKai Krakow void bch_btree_exit(void)
2771*9f233ffeSKai Krakow {
2772*9f233ffeSKai Krakow 	if (btree_io_wq)
2773*9f233ffeSKai Krakow 		destroy_workqueue(btree_io_wq);
2774*9f233ffeSKai Krakow }
2775*9f233ffeSKai Krakow 
2776*9f233ffeSKai Krakow int __init bch_btree_init(void)
2777*9f233ffeSKai Krakow {
2778*9f233ffeSKai Krakow 	btree_io_wq = create_singlethread_workqueue("bch_btree_io");
2779*9f233ffeSKai Krakow 	if (!btree_io_wq)
2780*9f233ffeSKai Krakow 		return -ENOMEM;
2781*9f233ffeSKai Krakow 
2782*9f233ffeSKai Krakow 	return 0;
2783*9f233ffeSKai Krakow }
2784