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