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