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