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