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