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