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