]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_cache.c
Update bcachefs sources to e99d29e402 bcachefs: zstd support, compression refactoring
[bcachefs-tools-debian] / libbcachefs / btree_cache.c
1
2 #include "bcachefs.h"
3 #include "btree_cache.h"
4 #include "btree_io.h"
5 #include "btree_iter.h"
6 #include "btree_locking.h"
7 #include "debug.h"
8 #include "extents.h"
9
10 #include <linux/prefetch.h>
11 #include <trace/events/bcachefs.h>
12
13 #define DEF_BTREE_ID(kwd, val, name) name,
14
15 const char * const bch2_btree_ids[] = {
16         DEFINE_BCH_BTREE_IDS()
17         NULL
18 };
19
20 #undef DEF_BTREE_ID
21
22 void bch2_recalc_btree_reserve(struct bch_fs *c)
23 {
24         unsigned i, reserve = 16;
25
26         if (!c->btree_roots[0].b)
27                 reserve += 8;
28
29         for (i = 0; i < BTREE_ID_NR; i++)
30                 if (c->btree_roots[i].b)
31                         reserve += min_t(unsigned, 1,
32                                          c->btree_roots[i].b->level) * 8;
33
34         c->btree_cache.reserve = reserve;
35 }
36
37 static inline unsigned btree_cache_can_free(struct btree_cache *bc)
38 {
39         return max_t(int, 0, bc->used - bc->reserve);
40 }
41
42 static void __btree_node_data_free(struct bch_fs *c, struct btree *b)
43 {
44         EBUG_ON(btree_node_write_in_flight(b));
45
46         kvpfree(b->data, btree_bytes(c));
47         b->data = NULL;
48         bch2_btree_keys_free(b);
49 }
50
51 static void btree_node_data_free(struct bch_fs *c, struct btree *b)
52 {
53         struct btree_cache *bc = &c->btree_cache;
54
55         __btree_node_data_free(c, b);
56         bc->used--;
57         list_move(&b->list, &bc->freed);
58 }
59
60 static int bch2_btree_cache_cmp_fn(struct rhashtable_compare_arg *arg,
61                                    const void *obj)
62 {
63         const struct btree *b = obj;
64         const u64 *v = arg->key;
65
66         return PTR_HASH(&b->key) == *v ? 0 : 1;
67 }
68
69 static const struct rhashtable_params bch_btree_cache_params = {
70         .head_offset    = offsetof(struct btree, hash),
71         .key_offset     = offsetof(struct btree, key.v),
72         .key_len        = sizeof(struct bch_extent_ptr),
73         .obj_cmpfn      = bch2_btree_cache_cmp_fn,
74 };
75
76 static void btree_node_data_alloc(struct bch_fs *c, struct btree *b, gfp_t gfp)
77 {
78         struct btree_cache *bc = &c->btree_cache;
79
80         b->data = kvpmalloc(btree_bytes(c), gfp);
81         if (!b->data)
82                 goto err;
83
84         if (bch2_btree_keys_alloc(b, btree_page_order(c), gfp))
85                 goto err;
86
87         bc->used++;
88         list_move(&b->list, &bc->freeable);
89         return;
90 err:
91         kvpfree(b->data, btree_bytes(c));
92         b->data = NULL;
93         list_move(&b->list, &bc->freed);
94 }
95
96 static struct btree *btree_node_mem_alloc(struct bch_fs *c, gfp_t gfp)
97 {
98         struct btree *b = kzalloc(sizeof(struct btree), gfp);
99         if (!b)
100                 return NULL;
101
102         bkey_extent_init(&b->key);
103         six_lock_init(&b->lock);
104         INIT_LIST_HEAD(&b->list);
105         INIT_LIST_HEAD(&b->write_blocked);
106
107         btree_node_data_alloc(c, b, gfp);
108         return b->data ? b : NULL;
109 }
110
111 /* Btree in memory cache - hash table */
112
113 void bch2_btree_node_hash_remove(struct btree_cache *bc, struct btree *b)
114 {
115         rhashtable_remove_fast(&bc->table, &b->hash, bch_btree_cache_params);
116
117         /* Cause future lookups for this node to fail: */
118         bkey_i_to_extent(&b->key)->v._data[0] = 0;
119 }
120
121 int __bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b)
122 {
123         return rhashtable_lookup_insert_fast(&bc->table, &b->hash,
124                                              bch_btree_cache_params);
125 }
126
127 int bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b,
128                                 unsigned level, enum btree_id id)
129 {
130         int ret;
131
132         b->level        = level;
133         b->btree_id     = id;
134
135         mutex_lock(&bc->lock);
136         ret = __bch2_btree_node_hash_insert(bc, b);
137         if (!ret)
138                 list_add(&b->list, &bc->live);
139         mutex_unlock(&bc->lock);
140
141         return ret;
142 }
143
144 __flatten
145 static inline struct btree *btree_cache_find(struct btree_cache *bc,
146                                      const struct bkey_i *k)
147 {
148         return rhashtable_lookup_fast(&bc->table, &PTR_HASH(k),
149                                       bch_btree_cache_params);
150 }
151
152 /*
153  * this version is for btree nodes that have already been freed (we're not
154  * reaping a real btree node)
155  */
156 static int __btree_node_reclaim(struct bch_fs *c, struct btree *b, bool flush)
157 {
158         struct btree_cache *bc = &c->btree_cache;
159         int ret = 0;
160
161         lockdep_assert_held(&bc->lock);
162
163         if (!six_trylock_intent(&b->lock))
164                 return -ENOMEM;
165
166         if (!six_trylock_write(&b->lock))
167                 goto out_unlock_intent;
168
169         if (btree_node_noevict(b))
170                 goto out_unlock;
171
172         if (!btree_node_may_write(b))
173                 goto out_unlock;
174
175         if (btree_node_dirty(b) ||
176             btree_node_write_in_flight(b) ||
177             btree_node_read_in_flight(b)) {
178                 if (!flush)
179                         goto out_unlock;
180
181                 wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
182                                TASK_UNINTERRUPTIBLE);
183
184                 /*
185                  * Using the underscore version because we don't want to compact
186                  * bsets after the write, since this node is about to be evicted
187                  * - unless btree verify mode is enabled, since it runs out of
188                  * the post write cleanup:
189                  */
190                 if (verify_btree_ondisk(c))
191                         bch2_btree_node_write(c, b, SIX_LOCK_intent);
192                 else
193                         __bch2_btree_node_write(c, b, SIX_LOCK_read);
194
195                 /* wait for any in flight btree write */
196                 btree_node_wait_on_io(b);
197         }
198 out:
199         if (PTR_HASH(&b->key) && !ret)
200                 trace_btree_node_reap(c, b);
201         return ret;
202 out_unlock:
203         six_unlock_write(&b->lock);
204 out_unlock_intent:
205         six_unlock_intent(&b->lock);
206         ret = -ENOMEM;
207         goto out;
208 }
209
210 static int btree_node_reclaim(struct bch_fs *c, struct btree *b)
211 {
212         return __btree_node_reclaim(c, b, false);
213 }
214
215 static int btree_node_write_and_reclaim(struct bch_fs *c, struct btree *b)
216 {
217         return __btree_node_reclaim(c, b, true);
218 }
219
220 static unsigned long bch2_btree_cache_scan(struct shrinker *shrink,
221                                            struct shrink_control *sc)
222 {
223         struct bch_fs *c = container_of(shrink, struct bch_fs,
224                                         btree_cache.shrink);
225         struct btree_cache *bc = &c->btree_cache;
226         struct btree *b, *t;
227         unsigned long nr = sc->nr_to_scan;
228         unsigned long can_free;
229         unsigned long touched = 0;
230         unsigned long freed = 0;
231         unsigned i;
232
233         if (btree_shrinker_disabled(c))
234                 return SHRINK_STOP;
235
236         /* Return -1 if we can't do anything right now */
237         if (sc->gfp_mask & __GFP_IO)
238                 mutex_lock(&bc->lock);
239         else if (!mutex_trylock(&bc->lock))
240                 return -1;
241
242         /*
243          * It's _really_ critical that we don't free too many btree nodes - we
244          * have to always leave ourselves a reserve. The reserve is how we
245          * guarantee that allocating memory for a new btree node can always
246          * succeed, so that inserting keys into the btree can always succeed and
247          * IO can always make forward progress:
248          */
249         nr /= btree_pages(c);
250         can_free = btree_cache_can_free(bc);
251         nr = min_t(unsigned long, nr, can_free);
252
253         i = 0;
254         list_for_each_entry_safe(b, t, &bc->freeable, list) {
255                 touched++;
256
257                 if (freed >= nr)
258                         break;
259
260                 if (++i > 3 &&
261                     !btree_node_reclaim(c, b)) {
262                         btree_node_data_free(c, b);
263                         six_unlock_write(&b->lock);
264                         six_unlock_intent(&b->lock);
265                         freed++;
266                 }
267         }
268 restart:
269         list_for_each_entry_safe(b, t, &bc->live, list) {
270                 touched++;
271
272                 if (freed >= nr) {
273                         /* Save position */
274                         if (&t->list != &bc->live)
275                                 list_move_tail(&bc->live, &t->list);
276                         break;
277                 }
278
279                 if (!btree_node_accessed(b) &&
280                     !btree_node_reclaim(c, b)) {
281                         /* can't call bch2_btree_node_hash_remove under lock  */
282                         freed++;
283                         if (&t->list != &bc->live)
284                                 list_move_tail(&bc->live, &t->list);
285
286                         btree_node_data_free(c, b);
287                         mutex_unlock(&bc->lock);
288
289                         bch2_btree_node_hash_remove(bc, b);
290                         six_unlock_write(&b->lock);
291                         six_unlock_intent(&b->lock);
292
293                         if (freed >= nr)
294                                 goto out;
295
296                         if (sc->gfp_mask & __GFP_IO)
297                                 mutex_lock(&bc->lock);
298                         else if (!mutex_trylock(&bc->lock))
299                                 goto out;
300                         goto restart;
301                 } else
302                         clear_btree_node_accessed(b);
303         }
304
305         mutex_unlock(&bc->lock);
306 out:
307         return (unsigned long) freed * btree_pages(c);
308 }
309
310 static unsigned long bch2_btree_cache_count(struct shrinker *shrink,
311                                             struct shrink_control *sc)
312 {
313         struct bch_fs *c = container_of(shrink, struct bch_fs,
314                                         btree_cache.shrink);
315         struct btree_cache *bc = &c->btree_cache;
316
317         if (btree_shrinker_disabled(c))
318                 return 0;
319
320         return btree_cache_can_free(bc) * btree_pages(c);
321 }
322
323 void bch2_fs_btree_cache_exit(struct bch_fs *c)
324 {
325         struct btree_cache *bc = &c->btree_cache;
326         struct btree *b;
327         unsigned i;
328
329         if (bc->shrink.list.next)
330                 unregister_shrinker(&bc->shrink);
331
332         mutex_lock(&bc->lock);
333
334 #ifdef CONFIG_BCACHEFS_DEBUG
335         if (c->verify_data)
336                 list_move(&c->verify_data->list, &bc->live);
337
338         kvpfree(c->verify_ondisk, btree_bytes(c));
339 #endif
340
341         for (i = 0; i < BTREE_ID_NR; i++)
342                 if (c->btree_roots[i].b)
343                         list_add(&c->btree_roots[i].b->list, &bc->live);
344
345         list_splice(&bc->freeable, &bc->live);
346
347         while (!list_empty(&bc->live)) {
348                 b = list_first_entry(&bc->live, struct btree, list);
349
350                 BUG_ON(btree_node_read_in_flight(b) ||
351                        btree_node_write_in_flight(b));
352
353                 if (btree_node_dirty(b))
354                         bch2_btree_complete_write(c, b, btree_current_write(b));
355                 clear_btree_node_dirty(b);
356
357                 btree_node_data_free(c, b);
358         }
359
360         while (!list_empty(&bc->freed)) {
361                 b = list_first_entry(&bc->freed, struct btree, list);
362                 list_del(&b->list);
363                 kfree(b);
364         }
365
366         mutex_unlock(&bc->lock);
367
368         if (bc->table_init_done)
369                 rhashtable_destroy(&bc->table);
370 }
371
372 int bch2_fs_btree_cache_init(struct bch_fs *c)
373 {
374         struct btree_cache *bc = &c->btree_cache;
375         unsigned i;
376         int ret = 0;
377
378         pr_verbose_init(c->opts, "");
379
380         ret = rhashtable_init(&bc->table, &bch_btree_cache_params);
381         if (ret)
382                 goto out;
383
384         bc->table_init_done = true;
385
386         bch2_recalc_btree_reserve(c);
387
388         for (i = 0; i < bc->reserve; i++)
389                 if (!btree_node_mem_alloc(c, GFP_KERNEL)) {
390                         ret = -ENOMEM;
391                         goto out;
392                 }
393
394         list_splice_init(&bc->live, &bc->freeable);
395
396 #ifdef CONFIG_BCACHEFS_DEBUG
397         mutex_init(&c->verify_lock);
398
399         c->verify_ondisk = kvpmalloc(btree_bytes(c), GFP_KERNEL);
400         if (!c->verify_ondisk) {
401                 ret = -ENOMEM;
402                 goto out;
403         }
404
405         c->verify_data = btree_node_mem_alloc(c, GFP_KERNEL);
406         if (!c->verify_data) {
407                 ret = -ENOMEM;
408                 goto out;
409         }
410
411         list_del_init(&c->verify_data->list);
412 #endif
413
414         bc->shrink.count_objects        = bch2_btree_cache_count;
415         bc->shrink.scan_objects         = bch2_btree_cache_scan;
416         bc->shrink.seeks                = 4;
417         bc->shrink.batch                = btree_pages(c) * 2;
418         register_shrinker(&bc->shrink);
419 out:
420         pr_verbose_init(c->opts, "ret %i", ret);
421         return ret;
422 }
423
424 void bch2_fs_btree_cache_init_early(struct btree_cache *bc)
425 {
426         mutex_init(&bc->lock);
427         INIT_LIST_HEAD(&bc->live);
428         INIT_LIST_HEAD(&bc->freeable);
429         INIT_LIST_HEAD(&bc->freed);
430 }
431
432 /*
433  * We can only have one thread cannibalizing other cached btree nodes at a time,
434  * or we'll deadlock. We use an open coded mutex to ensure that, which a
435  * cannibalize_bucket() will take. This means every time we unlock the root of
436  * the btree, we need to release this lock if we have it held.
437  */
438 void bch2_btree_cache_cannibalize_unlock(struct bch_fs *c)
439 {
440         struct btree_cache *bc = &c->btree_cache;
441
442         if (bc->alloc_lock == current) {
443                 trace_btree_node_cannibalize_unlock(c);
444                 bc->alloc_lock = NULL;
445                 closure_wake_up(&bc->alloc_wait);
446         }
447 }
448
449 int bch2_btree_cache_cannibalize_lock(struct bch_fs *c, struct closure *cl)
450 {
451         struct btree_cache *bc = &c->btree_cache;
452         struct task_struct *old;
453
454         old = cmpxchg(&bc->alloc_lock, NULL, current);
455         if (old == NULL || old == current)
456                 goto success;
457
458         if (!cl) {
459                 trace_btree_node_cannibalize_lock_fail(c);
460                 return -ENOMEM;
461         }
462
463         closure_wait(&bc->alloc_wait, cl);
464
465         /* Try again, after adding ourselves to waitlist */
466         old = cmpxchg(&bc->alloc_lock, NULL, current);
467         if (old == NULL || old == current) {
468                 /* We raced */
469                 closure_wake_up(&bc->alloc_wait);
470                 goto success;
471         }
472
473         trace_btree_node_cannibalize_lock_fail(c);
474         return -EAGAIN;
475
476 success:
477         trace_btree_node_cannibalize_lock(c);
478         return 0;
479 }
480
481 static struct btree *btree_node_cannibalize(struct bch_fs *c)
482 {
483         struct btree_cache *bc = &c->btree_cache;
484         struct btree *b;
485
486         list_for_each_entry_reverse(b, &bc->live, list)
487                 if (!btree_node_reclaim(c, b))
488                         return b;
489
490         while (1) {
491                 list_for_each_entry_reverse(b, &bc->live, list)
492                         if (!btree_node_write_and_reclaim(c, b))
493                                 return b;
494
495                 /*
496                  * Rare case: all nodes were intent-locked.
497                  * Just busy-wait.
498                  */
499                 WARN_ONCE(1, "btree cache cannibalize failed\n");
500                 cond_resched();
501         }
502 }
503
504 struct btree *bch2_btree_node_mem_alloc(struct bch_fs *c)
505 {
506         struct btree_cache *bc = &c->btree_cache;
507         struct btree *b;
508         u64 start_time = local_clock();
509
510         mutex_lock(&bc->lock);
511
512         /*
513          * btree_free() doesn't free memory; it sticks the node on the end of
514          * the list. Check if there's any freed nodes there:
515          */
516         list_for_each_entry(b, &bc->freeable, list)
517                 if (!btree_node_reclaim(c, b))
518                         goto out_unlock;
519
520         /*
521          * We never free struct btree itself, just the memory that holds the on
522          * disk node. Check the freed list before allocating a new one:
523          */
524         list_for_each_entry(b, &bc->freed, list)
525                 if (!btree_node_reclaim(c, b)) {
526                         btree_node_data_alloc(c, b, __GFP_NOWARN|GFP_NOIO);
527                         if (b->data)
528                                 goto out_unlock;
529
530                         six_unlock_write(&b->lock);
531                         six_unlock_intent(&b->lock);
532                         goto err;
533                 }
534
535         b = btree_node_mem_alloc(c, __GFP_NOWARN|GFP_NOIO);
536         if (!b)
537                 goto err;
538
539         BUG_ON(!six_trylock_intent(&b->lock));
540         BUG_ON(!six_trylock_write(&b->lock));
541 out_unlock:
542         BUG_ON(btree_node_hashed(b));
543         BUG_ON(btree_node_write_in_flight(b));
544
545         list_del_init(&b->list);
546         mutex_unlock(&bc->lock);
547 out:
548         b->flags                = 0;
549         b->written              = 0;
550         b->nsets                = 0;
551         b->sib_u64s[0]          = 0;
552         b->sib_u64s[1]          = 0;
553         b->whiteout_u64s        = 0;
554         b->uncompacted_whiteout_u64s = 0;
555         bch2_btree_keys_init(b, &c->expensive_debug_checks);
556
557         bch2_time_stats_update(&c->btree_node_mem_alloc_time, start_time);
558
559         return b;
560 err:
561         /* Try to cannibalize another cached btree node: */
562         if (bc->alloc_lock == current) {
563                 b = btree_node_cannibalize(c);
564                 list_del_init(&b->list);
565                 mutex_unlock(&bc->lock);
566
567                 bch2_btree_node_hash_remove(bc, b);
568
569                 trace_btree_node_cannibalize(c);
570                 goto out;
571         }
572
573         mutex_unlock(&bc->lock);
574         return ERR_PTR(-ENOMEM);
575 }
576
577 /* Slowpath, don't want it inlined into btree_iter_traverse() */
578 static noinline struct btree *bch2_btree_node_fill(struct bch_fs *c,
579                                                    struct btree_iter *iter,
580                                                    const struct bkey_i *k,
581                                                    unsigned level,
582                                                    enum six_lock_type lock_type)
583 {
584         struct btree_cache *bc = &c->btree_cache;
585         struct btree *b;
586
587         /*
588          * Parent node must be locked, else we could read in a btree node that's
589          * been freed:
590          */
591         BUG_ON(!btree_node_locked(iter, level + 1));
592
593         b = bch2_btree_node_mem_alloc(c);
594         if (IS_ERR(b))
595                 return b;
596
597         bkey_copy(&b->key, k);
598         if (bch2_btree_node_hash_insert(bc, b, level, iter->btree_id)) {
599                 /* raced with another fill: */
600
601                 /* mark as unhashed... */
602                 bkey_i_to_extent(&b->key)->v._data[0] = 0;
603
604                 mutex_lock(&bc->lock);
605                 list_add(&b->list, &bc->freeable);
606                 mutex_unlock(&bc->lock);
607
608                 six_unlock_write(&b->lock);
609                 six_unlock_intent(&b->lock);
610                 return NULL;
611         }
612
613         /*
614          * If the btree node wasn't cached, we can't drop our lock on
615          * the parent until after it's added to the cache - because
616          * otherwise we could race with a btree_split() freeing the node
617          * we're trying to lock.
618          *
619          * But the deadlock described below doesn't exist in this case,
620          * so it's safe to not drop the parent lock until here:
621          */
622         if (btree_node_read_locked(iter, level + 1))
623                 btree_node_unlock(iter, level + 1);
624
625         bch2_btree_node_read(c, b, true);
626         six_unlock_write(&b->lock);
627
628         if (lock_type == SIX_LOCK_read)
629                 six_lock_downgrade(&b->lock);
630
631         return b;
632 }
633
634 /**
635  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
636  * in from disk if necessary.
637  *
638  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
639  *
640  * The btree node will have either a read or a write lock held, depending on
641  * the @write parameter.
642  */
643 struct btree *bch2_btree_node_get(struct bch_fs *c, struct btree_iter *iter,
644                                   const struct bkey_i *k, unsigned level,
645                                   enum six_lock_type lock_type)
646 {
647         struct btree_cache *bc = &c->btree_cache;
648         struct btree *b;
649         struct bset_tree *t;
650
651         /* btree_node_fill() requires parent to be locked: */
652         EBUG_ON(!btree_node_locked(iter, level + 1));
653         EBUG_ON(level >= BTREE_MAX_DEPTH);
654 retry:
655         rcu_read_lock();
656         b = btree_cache_find(bc, k);
657         rcu_read_unlock();
658
659         if (unlikely(!b)) {
660                 /*
661                  * We must have the parent locked to call bch2_btree_node_fill(),
662                  * else we could read in a btree node from disk that's been
663                  * freed:
664                  */
665                 b = bch2_btree_node_fill(c, iter, k, level, lock_type);
666
667                 /* We raced and found the btree node in the cache */
668                 if (!b)
669                         goto retry;
670
671                 if (IS_ERR(b))
672                         return b;
673         } else {
674                 /*
675                  * There's a potential deadlock with splits and insertions into
676                  * interior nodes we have to avoid:
677                  *
678                  * The other thread might be holding an intent lock on the node
679                  * we want, and they want to update its parent node so they're
680                  * going to upgrade their intent lock on the parent node to a
681                  * write lock.
682                  *
683                  * But if we're holding a read lock on the parent, and we're
684                  * trying to get the intent lock they're holding, we deadlock.
685                  *
686                  * So to avoid this we drop the read locks on parent nodes when
687                  * we're starting to take intent locks - and handle the race.
688                  *
689                  * The race is that they might be about to free the node we
690                  * want, and dropping our read lock on the parent node lets them
691                  * update the parent marking the node we want as freed, and then
692                  * free it:
693                  *
694                  * To guard against this, btree nodes are evicted from the cache
695                  * when they're freed - and PTR_HASH() is zeroed out, which we
696                  * check for after we lock the node.
697                  *
698                  * Then, bch2_btree_node_relock() on the parent will fail - because
699                  * the parent was modified, when the pointer to the node we want
700                  * was removed - and we'll bail out:
701                  */
702                 if (btree_node_read_locked(iter, level + 1))
703                         btree_node_unlock(iter, level + 1);
704
705                 if (!btree_node_lock(b, k->k.p, level, iter, lock_type))
706                         return ERR_PTR(-EINTR);
707
708                 if (unlikely(PTR_HASH(&b->key) != PTR_HASH(k) ||
709                              b->level != level ||
710                              race_fault())) {
711                         six_unlock_type(&b->lock, lock_type);
712                         if (bch2_btree_node_relock(iter, level + 1))
713                                 goto retry;
714
715                         return ERR_PTR(-EINTR);
716                 }
717         }
718
719         wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
720                        TASK_UNINTERRUPTIBLE);
721
722         prefetch(b->aux_data);
723
724         for_each_bset(b, t) {
725                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
726
727                 prefetch(p + L1_CACHE_BYTES * 0);
728                 prefetch(p + L1_CACHE_BYTES * 1);
729                 prefetch(p + L1_CACHE_BYTES * 2);
730         }
731
732         /* avoid atomic set bit if it's not needed: */
733         if (btree_node_accessed(b))
734                 set_btree_node_accessed(b);
735
736         if (unlikely(btree_node_read_error(b))) {
737                 six_unlock_type(&b->lock, lock_type);
738                 return ERR_PTR(-EIO);
739         }
740
741         EBUG_ON(!b->written);
742         EBUG_ON(b->btree_id != iter->btree_id ||
743                 BTREE_NODE_LEVEL(b->data) != level ||
744                 bkey_cmp(b->data->max_key, k->k.p));
745
746         return b;
747 }
748
749 struct btree *bch2_btree_node_get_sibling(struct bch_fs *c,
750                                           struct btree_iter *iter,
751                                           struct btree *b,
752                                           enum btree_node_sibling sib)
753 {
754         struct btree *parent;
755         struct btree_node_iter node_iter;
756         struct bkey_packed *k;
757         BKEY_PADDED(k) tmp;
758         struct btree *ret;
759         unsigned level = b->level;
760
761         parent = btree_iter_node(iter, level + 1);
762         if (!parent)
763                 return NULL;
764
765         if (!bch2_btree_node_relock(iter, level + 1)) {
766                 bch2_btree_iter_set_locks_want(iter, level + 2);
767                 return ERR_PTR(-EINTR);
768         }
769
770         node_iter = iter->l[parent->level].iter;
771
772         k = bch2_btree_node_iter_peek_all(&node_iter, parent);
773         BUG_ON(bkey_cmp_left_packed(parent, k, &b->key.k.p));
774
775         do {
776                 k = sib == btree_prev_sib
777                         ? bch2_btree_node_iter_prev_all(&node_iter, parent)
778                         : (bch2_btree_node_iter_advance(&node_iter, parent),
779                            bch2_btree_node_iter_peek_all(&node_iter, parent));
780                 if (!k)
781                         return NULL;
782         } while (bkey_deleted(k));
783
784         bch2_bkey_unpack(parent, &tmp.k, k);
785
786         ret = bch2_btree_node_get(c, iter, &tmp.k, level, SIX_LOCK_intent);
787
788         if (IS_ERR(ret) && PTR_ERR(ret) == -EINTR) {
789                 btree_node_unlock(iter, level);
790
791                 if (!bch2_btree_node_relock(iter, level + 1)) {
792                         bch2_btree_iter_set_locks_want(iter, level + 2);
793                         return ERR_PTR(-EINTR);
794                 }
795
796                 ret = bch2_btree_node_get(c, iter, &tmp.k, level, SIX_LOCK_intent);
797         }
798
799         if (!bch2_btree_node_relock(iter, level)) {
800                 btree_iter_set_dirty(iter, BTREE_ITER_NEED_RELOCK);
801
802                 if (!IS_ERR(ret)) {
803                         six_unlock_intent(&ret->lock);
804                         ret = ERR_PTR(-EINTR);
805                 }
806         }
807
808         return ret;
809 }
810
811 void bch2_btree_node_prefetch(struct bch_fs *c, const struct bkey_i *k,
812                               unsigned level, enum btree_id btree_id)
813 {
814         struct btree_cache *bc = &c->btree_cache;
815         struct btree *b;
816
817         BUG_ON(level >= BTREE_MAX_DEPTH);
818
819         rcu_read_lock();
820         b = btree_cache_find(bc, k);
821         rcu_read_unlock();
822
823         if (b)
824                 return;
825
826         b = bch2_btree_node_mem_alloc(c);
827         if (IS_ERR(b))
828                 return;
829
830         bkey_copy(&b->key, k);
831         if (bch2_btree_node_hash_insert(bc, b, level, btree_id)) {
832                 /* raced with another fill: */
833
834                 /* mark as unhashed... */
835                 bkey_i_to_extent(&b->key)->v._data[0] = 0;
836
837                 mutex_lock(&bc->lock);
838                 list_add(&b->list, &bc->freeable);
839                 mutex_unlock(&bc->lock);
840                 goto out;
841         }
842
843         bch2_btree_node_read(c, b, false);
844 out:
845         six_unlock_write(&b->lock);
846         six_unlock_intent(&b->lock);
847 }
848
849 int bch2_print_btree_node(struct bch_fs *c, struct btree *b,
850                           char *buf, size_t len)
851 {
852         const struct bkey_format *f = &b->format;
853         struct bset_stats stats;
854         char ptrs[100];
855
856         memset(&stats, 0, sizeof(stats));
857
858         bch2_val_to_text(c, BKEY_TYPE_BTREE, ptrs, sizeof(ptrs),
859                         bkey_i_to_s_c(&b->key));
860         bch2_btree_keys_stats(b, &stats);
861
862         return scnprintf(buf, len,
863                          "l %u %llu:%llu - %llu:%llu:\n"
864                          "    ptrs: %s\n"
865                          "    format: u64s %u fields %u %u %u %u %u\n"
866                          "    unpack fn len: %u\n"
867                          "    bytes used %zu/%zu (%zu%% full)\n"
868                          "    sib u64s: %u, %u (merge threshold %zu)\n"
869                          "    nr packed keys %u\n"
870                          "    nr unpacked keys %u\n"
871                          "    floats %zu\n"
872                          "    failed unpacked %zu\n"
873                          "    failed prev %zu\n"
874                          "    failed overflow %zu\n",
875                          b->level,
876                          b->data->min_key.inode,
877                          b->data->min_key.offset,
878                          b->data->max_key.inode,
879                          b->data->max_key.offset,
880                          ptrs,
881                          f->key_u64s,
882                          f->bits_per_field[0],
883                          f->bits_per_field[1],
884                          f->bits_per_field[2],
885                          f->bits_per_field[3],
886                          f->bits_per_field[4],
887                          b->unpack_fn_len,
888                          b->nr.live_u64s * sizeof(u64),
889                          btree_bytes(c) - sizeof(struct btree_node),
890                          b->nr.live_u64s * 100 / btree_max_u64s(c),
891                          b->sib_u64s[0],
892                          b->sib_u64s[1],
893                          BTREE_FOREGROUND_MERGE_THRESHOLD(c),
894                          b->nr.packed_keys,
895                          b->nr.unpacked_keys,
896                          stats.floats,
897                          stats.failed_unpacked,
898                          stats.failed_prev,
899                          stats.failed_overflow);
900 }