]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_cache.c
Update bcachefs sources to 916d92b6b4 bcachefs: Add error messages for memory allocat...
[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                 btree_trans_restart(trans);
670                 return ERR_PTR(-EINTR);
671         }
672
673         b = bch2_btree_node_mem_alloc(c);
674         if (IS_ERR(b))
675                 return b;
676
677         bkey_copy(&b->key, k);
678         if (bch2_btree_node_hash_insert(bc, b, level, btree_id)) {
679                 /* raced with another fill: */
680
681                 /* mark as unhashed... */
682                 b->hash_val = 0;
683
684                 mutex_lock(&bc->lock);
685                 list_add(&b->list, &bc->freeable);
686                 mutex_unlock(&bc->lock);
687
688                 six_unlock_write(&b->c.lock);
689                 six_unlock_intent(&b->c.lock);
690                 return NULL;
691         }
692
693         set_btree_node_read_in_flight(b);
694
695         six_unlock_write(&b->c.lock);
696         seq = b->c.lock.state.seq;
697         six_unlock_intent(&b->c.lock);
698
699         /* Unlock before doing IO: */
700         if (trans && sync)
701                 bch2_trans_unlock(trans);
702
703         bch2_btree_node_read(c, b, sync);
704
705         if (!sync)
706                 return NULL;
707
708         if (trans &&
709             (!bch2_trans_relock(trans) ||
710              !bch2_btree_path_relock_intent(trans, path))) {
711                 BUG_ON(!trans->restarted);
712                 return ERR_PTR(-EINTR);
713         }
714
715         if (!six_relock_type(&b->c.lock, lock_type, seq)) {
716                 btree_trans_restart(trans);
717                 return ERR_PTR(-EINTR);
718         }
719
720         return b;
721 }
722
723 static int lock_node_check_fn(struct six_lock *lock, void *p)
724 {
725         struct btree *b = container_of(lock, struct btree, c.lock);
726         const struct bkey_i *k = p;
727
728         return b->hash_val == btree_ptr_hash_val(k) ? 0 : -1;
729 }
730
731 static noinline void btree_bad_header(struct bch_fs *c, struct btree *b)
732 {
733         char buf1[200], buf2[100], buf3[100];
734
735         if (!test_bit(BCH_FS_INITIAL_GC_DONE, &c->flags))
736                 return;
737
738         bch2_bkey_val_to_text(&PBUF(buf1), c, bkey_i_to_s_c(&b->key));
739         bch2_bpos_to_text(&PBUF(buf2), b->data->min_key);
740         bch2_bpos_to_text(&PBUF(buf3), b->data->max_key);
741
742         bch2_fs_inconsistent(c, "btree node header doesn't match ptr\n"
743                              "btree %s level %u\n"
744                              "ptr: %s\n"
745                              "header: btree %s level %llu\n"
746                              "min %s max %s\n",
747                              bch2_btree_ids[b->c.btree_id], b->c.level,
748                              buf1,
749                              bch2_btree_ids[BTREE_NODE_ID(b->data)],
750                              BTREE_NODE_LEVEL(b->data),
751                              buf2, buf3);
752 }
753
754 static inline void btree_check_header(struct bch_fs *c, struct btree *b)
755 {
756         if (b->c.btree_id != BTREE_NODE_ID(b->data) ||
757             b->c.level != BTREE_NODE_LEVEL(b->data) ||
758             bpos_cmp(b->data->max_key, b->key.k.p) ||
759             (b->key.k.type == KEY_TYPE_btree_ptr_v2 &&
760              bpos_cmp(b->data->min_key,
761                       bkey_i_to_btree_ptr_v2(&b->key)->v.min_key)))
762                 btree_bad_header(c, b);
763 }
764
765 /**
766  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
767  * in from disk if necessary.
768  *
769  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
770  *
771  * The btree node will have either a read or a write lock held, depending on
772  * the @write parameter.
773  */
774 struct btree *bch2_btree_node_get(struct btree_trans *trans, struct btree_path *path,
775                                   const struct bkey_i *k, unsigned level,
776                                   enum six_lock_type lock_type,
777                                   unsigned long trace_ip)
778 {
779         struct bch_fs *c = trans->c;
780         struct btree_cache *bc = &c->btree_cache;
781         struct btree *b;
782         struct bset_tree *t;
783
784         EBUG_ON(level >= BTREE_MAX_DEPTH);
785
786         b = btree_node_mem_ptr(k);
787
788         /*
789          * Check b->hash_val _before_ calling btree_node_lock() - this might not
790          * be the node we want anymore, and trying to lock the wrong node could
791          * cause an unneccessary transaction restart:
792          */
793         if (likely(c->opts.btree_node_mem_ptr_optimization &&
794                    b &&
795                    b->hash_val == btree_ptr_hash_val(k)))
796                         goto lock_node;
797 retry:
798         b = btree_cache_find(bc, k);
799         if (unlikely(!b)) {
800                 /*
801                  * We must have the parent locked to call bch2_btree_node_fill(),
802                  * else we could read in a btree node from disk that's been
803                  * freed:
804                  */
805                 b = bch2_btree_node_fill(c, trans, path, k, path->btree_id,
806                                          level, lock_type, true);
807
808                 /* We raced and found the btree node in the cache */
809                 if (!b)
810                         goto retry;
811
812                 if (IS_ERR(b))
813                         return b;
814         } else {
815 lock_node:
816                 /*
817                  * There's a potential deadlock with splits and insertions into
818                  * interior nodes we have to avoid:
819                  *
820                  * The other thread might be holding an intent lock on the node
821                  * we want, and they want to update its parent node so they're
822                  * going to upgrade their intent lock on the parent node to a
823                  * write lock.
824                  *
825                  * But if we're holding a read lock on the parent, and we're
826                  * trying to get the intent lock they're holding, we deadlock.
827                  *
828                  * So to avoid this we drop the read locks on parent nodes when
829                  * we're starting to take intent locks - and handle the race.
830                  *
831                  * The race is that they might be about to free the node we
832                  * want, and dropping our read lock on the parent node lets them
833                  * update the parent marking the node we want as freed, and then
834                  * free it:
835                  *
836                  * To guard against this, btree nodes are evicted from the cache
837                  * when they're freed - and b->hash_val is zeroed out, which we
838                  * check for after we lock the node.
839                  *
840                  * Then, bch2_btree_node_relock() on the parent will fail - because
841                  * the parent was modified, when the pointer to the node we want
842                  * was removed - and we'll bail out:
843                  */
844                 if (btree_node_read_locked(path, level + 1))
845                         btree_node_unlock(path, level + 1);
846
847                 if (!btree_node_lock(trans, path, b, k->k.p, level, lock_type,
848                                      lock_node_check_fn, (void *) k, trace_ip)) {
849                         if (!trans->restarted)
850                                 goto retry;
851                         return ERR_PTR(-EINTR);
852                 }
853
854                 if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
855                              b->c.level != level ||
856                              race_fault())) {
857                         six_unlock_type(&b->c.lock, lock_type);
858                         if (bch2_btree_node_relock(trans, path, level + 1))
859                                 goto retry;
860
861                         trace_trans_restart_btree_node_reused(trans->ip,
862                                                               trace_ip,
863                                                               path->btree_id,
864                                                               &path->pos);
865                         btree_trans_restart(trans);
866                         return ERR_PTR(-EINTR);
867                 }
868         }
869
870         if (unlikely(btree_node_read_in_flight(b))) {
871                 u32 seq = b->c.lock.state.seq;
872
873                 six_unlock_type(&b->c.lock, lock_type);
874                 bch2_trans_unlock(trans);
875
876                 bch2_btree_node_wait_on_read(b);
877
878                 /*
879                  * should_be_locked is not set on this path yet, so we need to
880                  * relock it specifically:
881                  */
882                 if (trans &&
883                     (!bch2_trans_relock(trans) ||
884                      !bch2_btree_path_relock_intent(trans, path))) {
885                         BUG_ON(!trans->restarted);
886                         return ERR_PTR(-EINTR);
887                 }
888
889                 if (!six_relock_type(&b->c.lock, lock_type, seq))
890                         goto retry;
891         }
892
893         prefetch(b->aux_data);
894
895         for_each_bset(b, t) {
896                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
897
898                 prefetch(p + L1_CACHE_BYTES * 0);
899                 prefetch(p + L1_CACHE_BYTES * 1);
900                 prefetch(p + L1_CACHE_BYTES * 2);
901         }
902
903         /* avoid atomic set bit if it's not needed: */
904         if (!btree_node_accessed(b))
905                 set_btree_node_accessed(b);
906
907         if (unlikely(btree_node_read_error(b))) {
908                 six_unlock_type(&b->c.lock, lock_type);
909                 return ERR_PTR(-EIO);
910         }
911
912         EBUG_ON(b->c.btree_id != path->btree_id);
913         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
914         btree_check_header(c, b);
915
916         return b;
917 }
918
919 struct btree *bch2_btree_node_get_noiter(struct bch_fs *c,
920                                          const struct bkey_i *k,
921                                          enum btree_id btree_id,
922                                          unsigned level,
923                                          bool nofill)
924 {
925         struct btree_cache *bc = &c->btree_cache;
926         struct btree *b;
927         struct bset_tree *t;
928         int ret;
929
930         EBUG_ON(level >= BTREE_MAX_DEPTH);
931
932         if (c->opts.btree_node_mem_ptr_optimization) {
933                 b = btree_node_mem_ptr(k);
934                 if (b)
935                         goto lock_node;
936         }
937 retry:
938         b = btree_cache_find(bc, k);
939         if (unlikely(!b)) {
940                 if (nofill)
941                         goto out;
942
943                 b = bch2_btree_node_fill(c, NULL, NULL, k, btree_id,
944                                          level, SIX_LOCK_read, true);
945
946                 /* We raced and found the btree node in the cache */
947                 if (!b)
948                         goto retry;
949
950                 if (IS_ERR(b) &&
951                     !bch2_btree_cache_cannibalize_lock(c, NULL))
952                         goto retry;
953
954                 if (IS_ERR(b))
955                         goto out;
956         } else {
957 lock_node:
958                 ret = six_lock_read(&b->c.lock, lock_node_check_fn, (void *) k);
959                 if (ret)
960                         goto retry;
961
962                 if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
963                              b->c.btree_id != btree_id ||
964                              b->c.level != level)) {
965                         six_unlock_read(&b->c.lock);
966                         goto retry;
967                 }
968         }
969
970         /* XXX: waiting on IO with btree locks held: */
971         __bch2_btree_node_wait_on_read(b);
972
973         prefetch(b->aux_data);
974
975         for_each_bset(b, t) {
976                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
977
978                 prefetch(p + L1_CACHE_BYTES * 0);
979                 prefetch(p + L1_CACHE_BYTES * 1);
980                 prefetch(p + L1_CACHE_BYTES * 2);
981         }
982
983         /* avoid atomic set bit if it's not needed: */
984         if (!btree_node_accessed(b))
985                 set_btree_node_accessed(b);
986
987         if (unlikely(btree_node_read_error(b))) {
988                 six_unlock_read(&b->c.lock);
989                 b = ERR_PTR(-EIO);
990                 goto out;
991         }
992
993         EBUG_ON(b->c.btree_id != btree_id);
994         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
995         btree_check_header(c, b);
996 out:
997         bch2_btree_cache_cannibalize_unlock(c);
998         return b;
999 }
1000
1001 int bch2_btree_node_prefetch(struct bch_fs *c,
1002                              struct btree_trans *trans,
1003                              struct btree_path *path,
1004                              const struct bkey_i *k,
1005                              enum btree_id btree_id, unsigned level)
1006 {
1007         struct btree_cache *bc = &c->btree_cache;
1008         struct btree *b;
1009
1010         BUG_ON(trans && !btree_node_locked(path, level + 1));
1011         BUG_ON(level >= BTREE_MAX_DEPTH);
1012
1013         b = btree_cache_find(bc, k);
1014         if (b)
1015                 return 0;
1016
1017         b = bch2_btree_node_fill(c, trans, path, k, btree_id,
1018                                  level, SIX_LOCK_read, false);
1019         return PTR_ERR_OR_ZERO(b);
1020 }
1021
1022 void bch2_btree_node_evict(struct bch_fs *c, const struct bkey_i *k)
1023 {
1024         struct btree_cache *bc = &c->btree_cache;
1025         struct btree *b;
1026
1027         b = btree_cache_find(bc, k);
1028         if (!b)
1029                 return;
1030 wait_on_io:
1031         /* not allowed to wait on io with btree locks held: */
1032
1033         /* XXX we're called from btree_gc which will be holding other btree
1034          * nodes locked
1035          * */
1036         __bch2_btree_node_wait_on_read(b);
1037         __bch2_btree_node_wait_on_write(b);
1038
1039         six_lock_intent(&b->c.lock, NULL, NULL);
1040         six_lock_write(&b->c.lock, NULL, NULL);
1041
1042         if (btree_node_dirty(b)) {
1043                 __bch2_btree_node_write(c, b, false);
1044                 six_unlock_write(&b->c.lock);
1045                 six_unlock_intent(&b->c.lock);
1046                 goto wait_on_io;
1047         }
1048
1049         BUG_ON(btree_node_dirty(b));
1050
1051         mutex_lock(&bc->lock);
1052         btree_node_data_free(c, b);
1053         bch2_btree_node_hash_remove(bc, b);
1054         mutex_unlock(&bc->lock);
1055
1056         six_unlock_write(&b->c.lock);
1057         six_unlock_intent(&b->c.lock);
1058 }
1059
1060 void bch2_btree_node_to_text(struct printbuf *out, struct bch_fs *c,
1061                              struct btree *b)
1062 {
1063         const struct bkey_format *f = &b->format;
1064         struct bset_stats stats;
1065
1066         memset(&stats, 0, sizeof(stats));
1067
1068         bch2_btree_keys_stats(b, &stats);
1069
1070         pr_buf(out, "l %u ", b->c.level);
1071         bch2_bpos_to_text(out, b->data->min_key);
1072         pr_buf(out, " - ");
1073         bch2_bpos_to_text(out, b->data->max_key);
1074         pr_buf(out, ":\n"
1075                "    ptrs: ");
1076         bch2_val_to_text(out, c, bkey_i_to_s_c(&b->key));
1077
1078         pr_buf(out, "\n"
1079                "    format: u64s %u fields %u %u %u %u %u\n"
1080                "    unpack fn len: %u\n"
1081                "    bytes used %zu/%zu (%zu%% full)\n"
1082                "    sib u64s: %u, %u (merge threshold %u)\n"
1083                "    nr packed keys %u\n"
1084                "    nr unpacked keys %u\n"
1085                "    floats %zu\n"
1086                "    failed unpacked %zu\n",
1087                f->key_u64s,
1088                f->bits_per_field[0],
1089                f->bits_per_field[1],
1090                f->bits_per_field[2],
1091                f->bits_per_field[3],
1092                f->bits_per_field[4],
1093                b->unpack_fn_len,
1094                b->nr.live_u64s * sizeof(u64),
1095                btree_bytes(c) - sizeof(struct btree_node),
1096                b->nr.live_u64s * 100 / btree_max_u64s(c),
1097                b->sib_u64s[0],
1098                b->sib_u64s[1],
1099                c->btree_foreground_merge_threshold,
1100                b->nr.packed_keys,
1101                b->nr.unpacked_keys,
1102                stats.floats,
1103                stats.failed);
1104 }
1105
1106 void bch2_btree_cache_to_text(struct printbuf *out, struct bch_fs *c)
1107 {
1108         pr_buf(out, "nr nodes:\t\t%u\n", c->btree_cache.used);
1109         pr_buf(out, "nr dirty:\t\t%u\n", atomic_read(&c->btree_cache.dirty));
1110         pr_buf(out, "cannibalize lock:\t%p\n", c->btree_cache.alloc_lock);
1111 }