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