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