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