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